NSMutableString stringWithString:NSString not working for me - iphone

This piece of code below is causing my app to crash
EDIT
#interface termsAndConditions : NSObject
{
NSMutableString *titleText;
NSMutableString *bodyText;
NSMutableArray *arrayBodyText;
}
#property (nonatomic, copy) NSMutableString *titleText;
#property (nonatomic, copy) NSMutableString *bodyText;
*EDIT*
else if ([[self.arrayBodyText objectAtIndex:x] isKindOfClass:[NSString class]])
{
if (x == 0)
{
self.bodyText=[NSMutableString stringWithString:[self.arrayBodyText
objectAtIndex:x]];
}
else
{
[self.bodyText appendString:[self.arrayBodyText objectAtIndex:x] ];
}
the arrayBodyText is an array of NSString which I got from a dictionary and that I want to join them altogether in 1 NSMutableString.
When the app crashes it gives the message :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendString:'
* Call stack at first throw:
Basically I need help to read this array of NSStrings into 1 NSMutableString.
Thanks
-Code

Do this:
self.bodyText = [[[self.arrayBodyText componentsJoinedByString:#""] mutableCopy] autorelease];

Related

How to create PFObject <SubClassing> with NSDictionary

I Have a PFobject subclassing registered in AppDelegate but when I try to set a NSDictionary, it crash with message:
'NSInvalidArgumentException', reason: 'PFObject values must be serializable to JSON'
Does anyone know how to do it right, using PFObject with ???
Here's my class:
Ranking.h
#interface Ranking : PFObject<PFSubclassing>
#property (nonatomic, retain) NSDictionary *final;
#end
Ranking.m
#implementation Ranking
#dynamic final;
+(NSString *)parseClassName{
return #"FinalRanking";
}
#end
And here's the method:
-(void)saveNewRanking{
Ranking *newRanking = [[Ranking alloc]init];
NSDictionary *dic = #{#1:#20,
#2:#18};
newRanking.final = dic;
[newRanking saveInBackground];
}

NSMutableDictionary + NSMutableArray crash

I have an NSMutableDictionary called "myScheduleFullDictionary" set up like this:
KEY VALUE
"Day 1" An NSMutableArray of NSMutableDictionaries
"Day 2" An NSMutableArray of NSMutableDictionaries
"Day 3" An NSMutableArray of NSMutableDictionaries
etc.
I'm trying to parse it - basically grab one of the MutableArrays contained as the Value of one of the Keys.
Here is my code:
// First I make a mutableCopy of the entire Dictionary:
NSMutableDictionary *copyOfMyScheduleDictionary = [myScheduleFullDictionary mutableCopy];
// Next I grab & sort all the KEYS from it:
NSArray *dayKeysArray = [[copyOfMyScheduleDictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
// I set up an NSMutableArray to hold the MutableArray I want to grab:
NSMutableArray *sessionsInThatDayArray = [[NSMutableArray alloc] init];
// Then I iterate through the KEYs and compare each to the one I'm searching for:
for (int i = 0; i < [dayKeysArray count]; i++) {
NSString *currentDayKey = [dayKeysArray objectAtIndex:i];
if ([currentDayKey isEqualToString: targetDayString]) {
NSLog(#"FOUND MATCH!!!");
// I log out the NSMutableArray I found - which works perfectly:
NSLog(#"found array is: %#", [copyOfMyScheduleDictionary objectForKey:currentDayKey]);
// But when I try to actually grab it, everything crashes:
sessionsInThatDayArray = [copyOfMyScheduleDictionary objectForKey:currentDayKey];
break;
}
}
The error I get is:
-[__NSDictionaryM name]: unrecognized selector sent to instance 0x1c5fb2d0
Not sure why its pointing out "name" as the "unrecognized selector." "name" is an NSString property of a "Session" class I declared and am working with - could that be related somehow?
Any insights?
EDIT:
Here is my "SessionObject" class definition:
#interface SessionObject : NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) NSString *speaker;
#property (nonatomic, strong) NSString *location;
#property (nonatomic, strong) NSDate *startTime, *endTime;
#property (nonatomic, strong) NSString *notes;
#property (nonatomic, strong) NSString *dayOfConference;
#end
-[__NSDictionaryM name]: unrecognized selector sent to instance 0x1c5fb2d0
This means that you are trying to call name on an NSMutableDictionary where as you should have called it on an object of class SessionObject. Check the line where you are calling something like myObject.name or [myObject name] and see if myObject is of type SessionObject and not NSMutableDictionary.
Here __NSDictionaryM denotes the NSMutableDictionary type.
I'm not sure where your bug comes from - but what are you doing there? Why don't you just write
sessionsInThatDayArray = [myScheduleFullDictionary objectForKey:targetDayString];
??? That's what NSDictionary is there for - you don't search for things by hand, you just call the method to look up the key. Instead you copied the dictionary, you extracted all the keys, you sorted the keys, you iterated through them one by one until you found it - and then you called objectForKey!!!
Apart from that, in the debugger set a breakpoint on all Objective-C exceptions. It will stop when the offending code is called, so no need to search for a needle in the haystack.

How do I get out data from my NSDirectory (not just a property typo)?

I'm missing something simple I think, but been at it for days now without solving this. Even Started to create a "work-around" just to solve it for now, but still want to solve this the "right" way. Any suggestions? Thank's!
.
The problem:
Seems to be missing the class Adealer (get error "-[Adealer objectAtIndex:]: unrecognized selector sent to instance 0x8c5f8b0"), but I did the import Adealer.h to this "detailsVC". But it's not just a simple error of naming the property wrong (objectForKey:#"CustName" instead of "custname" etc - tested this a lot).
Also, I've got similar "listVC"s without a class like Adealer in them, that also transfer data the same way to the same "detailsVC" and they work just fine! Then I just get the data with calls like;
self.labelRestName.text = [restDetails objectForKey:#"CustName"];
Overview:
I got a tableViewController "listVC" that creates the data and show a list, then a ViewController "detailsVC" to show the details. The data (selected row object in "listVC" is transfered via a seque and "destVC.restGPSTransfer" (NSDictionary). The data arrives ok in the "detailsVC" and looks like this in the terminal;
dealerName = Uppsala Centrum Test
dealerAdressStreet = Dragarbrunnsgatan 55
dealerAdressZip = 75320
dealerAdressCity = Uppsala
dealerLongitude = 17.63893
dealerLatitude = 59.85856
dealerDistance2 = 8586398.000000
etc
.
Following the data:
"listVC"
1) First fetching data from web via a AFNetworking json object into an NSMutableArray "restFeed" - ok.
2) Then creating my own data to an NSMutableArray within this loop into a NSMutableArray "updatedDealers" - ok;
NSMutableArray *updatedDealers = [[NSMutableArray alloc]init];
while (i+1 < [_restFeed count]) {
i++;
// Get dealer position function here
// Get distance function here
// Then create my own data here (also #imported Adealer to "listVC";
Adealer *theDealer = [[Adealer alloc]init];
theDealer.dealerName = [[_restFeed objectAtIndex:i]objectForKey:#"CustName"];
theDealer.dealerLongitude = [[_restFeed objectAtIndex:i]objectForKey:#"long"];
theDealer.dealerLatitude = [[_restFeed objectAtIndex:i]objectForKey:#"lat"];
theDealer.dealerDistance2 = theDistance;
// etc...
// Check if data ok
NSLog(#"theDealer = %#",[theDealer description]);
// Don't add dealer object without positiondata to the new array
if (![theDealer.dealerLatitude isEqualToString:#""]) {
[updatedDealers addObject:theDealer];
}
3) Then I use NSSortdescriptor to sort the dealers in NSMutableArray "updatedDealers" into distance order and finally creates the new NSMutableArray "restFeed" with this; (also did "#synthesize dealerFeed = _dealerFeed;" in "listVC") - ok.
_dealerFeed = [NSMutableArray arrayWithArray:sortedContestArray];
4) The populating some tableViewCells with this array and it works just fine - ok.;
cell.cellDealerName.text = [NSString stringWithFormat:#"%#",[[_dealerFeed objectAtIndex:indexPath.row]dealerName]];
5) In the function didSelectRowAtIndexPath transfer the selected object with the "detailsVC"'s NSDictionary "restGPSTransfer" - ok;
destVC.restGPSTransfer = [_dealerFeed objectAtIndex:myIndexPath.row];
"detailsVC":
6) The data seems to transfer ok (se top of this post) but when trying to call the data with;
self.labelRestName.text = [restGPSTransfer objectForKey:#"dealerName"];
I get this error and the app crashes: "-[Adealer objectAtIndex:]: unrecognized selector sent to instance 0x8c5f8b0".
Some more testing done...
Tried to verify the structure + it's keys and properties of the NSDictionary "restGPSTransfer", but using description only got me so far. And have not solved my problem and I still get the "unrecognized selector" error. Could it maybe have become dictionaries within dictionary's or something?
Constructed this little simple if-test to see if the property is really there. But I have to check every property "manually". There's propably a smarter way to check the hole NSDictionary / NSArray?
if ([restGPSTransfer objectForKey:#"dealerName"]) {
NSLog(#"= YES! key exists.");
} else {
NSLog(#"= Nope! key don't exists");
}
THANK'S for any help on this :-)
.
UPDATE the Adealer class files;
Adealer.h
#import <Foundation/Foundation.h>
#interface Adealer : NSObject
#property (nonatomic, retain) NSString * dealerName;
#property (nonatomic, retain) NSString * dealerAdressCity;
#property (nonatomic, retain) NSString * dealerAdressStreet;
#property (nonatomic, retain) NSString * dealerAdressZip;
#property (nonatomic, retain) NSNumber * dealerID;
#property (nonatomic, retain) NSString * dealerImages;
#property (nonatomic, retain) NSString * dealerLogo;
#property (nonatomic, retain) NSString * dealerMail;
#property (nonatomic, retain) NSString * dealerProducts;
#property (nonatomic, retain) NSString * dealerTel;
#property (nonatomic, retain) NSString * dealerText;
#property (nonatomic, retain) NSString * dealerWeb;
#property (nonatomic, retain) NSString * dealerLongitude;
#property (nonatomic, retain) NSString * dealerLatitude;
#property (nonatomic, retain) NSString *dealerDistance;
#property float dealerDistance2;
#end
Adealer.m
#import "Adealer.h"
#implementation Adealer
#synthesize dealerAdressCity, dealerAdressStreet, dealerAdressZip, dealerID, dealerImages, dealerLogo;
#synthesize dealerMail, dealerName, dealerProducts, dealerTel, dealerText, dealerWeb;
#synthesize dealerLongitude, dealerLatitude, dealerDistance,dealerDistance2;
- (NSString *)description {
// Added extension of description
NSMutableString *string = [NSMutableString string];
[string appendString:#"\ntheDealer object and it's properties:\n"];
[string appendFormat:#"dealerName = %#\n", dealerName];
[string appendFormat:#"dealerAdressStreet = %#\n", dealerAdressStreet];
[string appendFormat:#"dealerAdressZip = %#\n", dealerAdressZip];
[string appendFormat:#"dealerAdressCity = %#\n", dealerAdressCity];
[string appendFormat:#"dealerTel = %#\n", dealerTel];
[string appendFormat:#"dealerMail = %#\n", dealerMail];
[string appendFormat:#"dealerWeb = %#\n", dealerWeb];
[string appendFormat:#"dealerLogo = %#\n", dealerLogo];
[string appendFormat:#"dealerImages = %#\n", dealerImages];
[string appendFormat:#"dealerText = %#\n", dealerText];
[string appendFormat:#"dealerProducts = %#\n", dealerProducts];
[string appendFormat:#"dealerLongitude = %#\n", dealerLongitude];
[string appendFormat:#"dealerLatitude = %#\n", dealerLatitude];
[string appendFormat:#"dealerDistance = %#\n", dealerDistance];
[string appendFormat:#"dealerDistance2 = %f\n\n", dealerDistance2];
return string;
}
#end
SOLVED!
Posted if anyone else needs it here.
The solution
In my "detailsVC" I first did this iVar declaration;
.h:
Adealer *theDealer;
#property (nonatomic, retain) Adealer *theDealer;
.m:
#synthesize theDealer;
Then in my "listVC" i did this to transfer the Adealer object and it's properties to the "detailsVC" (remember that the Adealer object already has got it's properties earlier in the described "loop");
Instead of my earlier;
destVC.restGPSTransfer = [_dealerFeed objectAtIndex:myIndexPath.row];
I changed it to;
destVC.theDealer = [_dealerFeed objectAtIndex:myIndexPath.row];
And to actually show and check the transferred property in "detailsVC" I can now simply call this to get the dealers name (or any other properties);
self.labelRestName.text = theDealer.dealerName;
NSLog(#"theDealer.name = %#",theDealer.dealerName);
Works great! Happy Coding everyone!

Why is my app crashing when I add a new managed object to a relationship set?

I've this simple Core Data Model:
Question, Answer
Every every question has 4 answers.
The code is the following:
Question.m
#interface Question : NSManagedObject
{
}
#property (nonatomic, retain) NSString * questionText;
#property (nonatomic, retain) NSSet* answers;
#property (nonatomic, retain) Package * package;
#end
#interface Question (CoreDataGeneratedAccessors)
- (void)addAnswersObject:(NSManagedObject *)value;
- (void)removeAnswersObject:(NSManagedObject *)value;
- (void)addAnswers:(NSSet *)value;
- (void)removeAnswers:(NSSet *)value;
#end
Answer.m
#class Question;
#interface Answer : NSManagedObject
{
}
#property (nonatomic, retain) NSString * answerText;
#property (nonatomic, retain) NSNumber * correct;
#property (nonatomic, retain) Question * question;
#end
The problem is when i try to add an answer to a question with addAnswersObject.
This is the part of the code that crash the app:
for (CXMLElement *theElement in theNodes)
{
Question *qst = [NSEntityDescription insertNewObjectForEntityForName:#"Question" inManagedObjectContext:moc];
// Create a counter variable as type "int"
int counter;
// Loop through the children of the current node
for(counter = 0; counter < [theElement childCount]; counter++) {
if([[[theElement childAtIndex:counter] name] isEqualToString: #"question"])
[qst setQuestionText:[[theElement childAtIndex:counter] stringValue]];
if([[[theElement childAtIndex:counter] name] isEqualToString: #"answer"]) {
Answer *answer = [NSEntityDescription insertNewObjectForEntityForName:#"Answer" inManagedObjectContext:moc];
[answer setAnswerText:[[theElement childAtIndex:counter] stringValue]];
CXMLElement *answerElement = (CXMLElement *)[theElement childAtIndex:counter];
if([[[answerElement attributeForName:#"correct"] stringValue] isEqualToString:#"YES"]) {
[answer setCorrect:[NSNumber numberWithBool:YES]];
} else {
[answer setCorrect:[NSNumber numberWithBool:NO]];
}
[qst addAnswersObject:answer]; //The app crash here
}
}
This is the log from console:
2010-05-24 20:02:38.475 Fgq[5670:40b]
*** -[NSUserDefaults objectForKey:]: message sent to deallocated instance
0x3c179a0 Program received signal:
“EXC_BAD_ACCESS”.
I re-exported many times all objects from the Object Data Model without success, I've checked all relationships and it seems that everything is ok.
What kind of problem could be?
What does the Console report if you add NSLog(#"qst: %#:, qst); immediately after the qst instance's -insertNewObjectForEntityName:inManagedObjectContext: call?
What does the Console report if you add NSLog(#"answer: %#:, answer); immediately after the answer instance's -insertNewObjectForEntityName:inManagedObjectContext: call?
Here what is reported with NSLog(#"qst: %#", qst);
2010-05-24 23:37:33.948
FGQ[452:207] qst:
(entity:
Question; id: 0x3c19ab0
; data: {
answers = (
);
package = nil;
questionText = nil; })

objective C filling array with custom class pointers

favorites = [[NSMutableArray alloc] init];
for (int i=0; i<9; i++) {
[favorites addObject:[[[Favorite alloc] constructUnknown] autorelease]];
}
i'm getting:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[Favorite size]: unrecognized selector sent to instance 0x380d9c0'
why?
Favorite is my custom class, favorites an array containing 9 instances of my custom class
edit:
Favorite.h:
-(Favorite*)constructUnknown;
Favorite.m:
- (Favorite*)constructUnknown{
self=[super init];
if (self) {
image=[UIImage imageNamed:#"unknown.png"];
}
return self;
}
COMPLETE FAVORITES.h
#interface Favorite : NSObject {
NSString *identity;
bool ready;
UIImage *image;
NSURL *telephone;
}
#property (nonatomic,retain) UIImage *image;
#property (nonatomic,retain) NSURL *telephone;
#property (nonatomic,retain) NSString *identity;
//passare unknown al nome per costrutire un oggetto unknown.
-(Favorite*)constructWithID:(NSString*)name withPhoto:(UIImage*)photo andNumber:(NSString*)number;
-(Favorite*)constructUnknown;
-(NSURL*) convertToUrl:(NSString*)phone;
- (UIImage*) getImage;
#end
The exception is likely because your image is not retained. Try
image = [[UIImage imageNamed:#"unknown.png"] retain];
BTW, initializers should be named as -initXXX and return an id by convention. e.g.
-(id)initWithUnknown{ ... }
Just in case someone reads this and still doesn't reach a solution, my problem was a little different I declared the object as:
#class LoginViewController;
#interface LoginViewDelegate : NSObject <UIApplicationDelegate> {
}
....
#property (nonatomic, retain) AppConfiguration *CurrentAppConfig;
....
#End
And when I was calling it:
[[self.CurrentAppConfig alloc] init];
I was getting the same error, all I had to do was use the synthesize keyword:
#implementation LoginViewDelegate
....
#synthesize CurrentAppConfig;