Application crashes when using NSMutableString - objective-c

in a header file I defined
NSMutableArray *numbers;
In the implementation I initialize this array first in the init method
numbers = [[NSMutableArray alloc] init];
I add strings to this array
[numbers insertObject:number atIndex:[numbers count]];
But when I access the array like this in another method
NSLog(#"%#", [numbers count]);
the application crashes. Any idea why this happens?

You are wrong here -
NSLog(#"%#", [numbers count]);
Array count is an integer value. Use %d instead of %# to print integer.
NSLog(#"%d", [numbers count]);

Your format string doesn't match the type of the second parameter.
[numbers count] returns an integer, not an object.
The " %#" format specifier indicates that the corresponding argument is an object, and that object will be sent a -description message. The string returned from that message expression will be inserted in place of the "%#". Your app crashes because it tries to send a message to an invalid receiver.

Related

NSNumberFormatter is not returning a sensible answer when converting a string

I have a UITextField, which I am trying to use a NSNumberFormatter with a NSNumberFormatterDecimalStyle to convert the text field into an NSNumber to initialise an object.
However when I do this, I can't get any sensible results out of the conversion. For the purpose of this example I have replaced the UITextField with a string, but I still get strange results. I am sure I am doing something daft, but any help would be appreciated.
//NSString * boardNumberText = self.txtBoardNumbs.text;
NSString * boardNumberText = #"42";
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * boardNumber = [formatter numberFromString:boardNumberText];
if ([boardNumber isEqual:nil]) {
NSLog(#"Number was null");
}
NSLog(#"Number was not null");
[self.board setNumber:boardNumber];
NSLog(boardNumberText);
NSLog([NSString stringWithFormat:#"%d", boardNumber]);
NSLog([NSString stringWithFormat:#"%d", self.board.number]);
The output that I get from the log file when I run this is:
2012-07-15 16:54:26.564 CoreDataDev[16123:fb03] Number was not null
2012-07-15 16:54:26.564 CoreDataDev[16123:fb03] 42
2012-07-15 16:54:26.565 CoreDataDev[16123:fb03] 135821152
2012-07-15 16:54:26.565 CoreDataDev[16123:fb03] 135820272
You can't just log NSNumber to the console using the integer format specifier, since NSNumber is a wrapper object. Also, NSLog takes a format string, so you don't need to use stringWithFormat:. Try this instead:
NSLog(#"%d", [boardNumber intValue]);
Using
NSLog(#"%d", boardNumber);
is wrong: it prints the memory address of the boardNumber pointer (the NSNumber instance itself). Use
NSLog(#"%d", [boardNumber intValue]);
instead.
P. s.: that
NSLog([NSString stringWithFormat:...]);
is unnecessary and ugly; NSLog has built-in format string handling, use it!

NSMutableArray not being saved

I'm trying to insert objects (NSNumbers) into an NSMutable array, but when I check it, the objectAtElement always returns 0.
NSNumber *indexNum = [NSNumber numberWithInt:indexInt];
[last100 insertObject:indexNum atIndex:prevCount];
NSLog(#"Entry #%d : %d", prevCount, (int)[last100 objectAtIndex:prevCount]);
prevCount++;
indexInt is coming in through the method, I already checked it and its valid. indexNum has also been checked and matches indexInt. The problem is NSLog(#"Entry #%d : %d", prevCount, (int)[last100 objectAtIndex:prevCount]); which always returns
2012-01-08 14:08:11.551 ThoughtSpreader[20746:fb03] Entry #9 : 0 The entry number will change, but the 0 is always there.
Oh, I also checked [last100 count] after every time I insert something new into it, and it always returns 0, so I believe its a problem with how I'm inserting something into the NSMutable array
If your count always returns 0 the likelihood is you haven't actually instantiated your NSMutableArray.
NSMutableArray *array = [NSMutableArray array];
[array addObject:[NSNumber numberWithInt:1]];
NSLog(#"%lu", [array count]); // Count => 1
//-------
array = nil;
[array addObject:[NSNumber numberWithInt:1]]; // Calling methods on nil is a no-op
NSLog(#"%lu", [array count]); // Count => 0
Updated %d to %lu thanks to #markhunte - it's hard to remember the finer details without testing it
Use
[[last100 objectAtIndex:prevCount] intValue]
instead of
(int)[last100 objectAtIndex:prevCount] - this explict conversion won't work.
[... intValue] is the message of NSNUmber which converts it to int.
NSNumber is an object, you can't just cast it to an int. Use intValue:
NSLog(#"Entry #%d : %d", prevCount, [[last100 objectAtIndex:prevCount] intValue]);

Grabbing a specific element of an array in Objective-C

I'm splitting a string by ';', but want to specifically grab the first and second element.
I know with PHP it's just simply $array[0], just can't find anything for this for Objective-C
NSArray *tempArray = [returnString componentsSeparatedByString:#";"];
So here I have assigned my array, how can I go about getting the first and second element?
Its just simply [array objectAtIndex:0] in Objective-C ;-)
Starting with XCode 4.5 (and Clang 3.3), you may use Objective-C Literals:
NSString *tmpString1 = tempArray[1];
NSString *tmpString = [tempArray objectAtIndex:0];
NSLog(#"String at index 0 = %#", tmpString);
NSString *tmpString1 = [tempArray objectAtIndex:1];
NSLog(#"String at index 1 = %#", tmpString1);
You may also wish to do an IF statement to check tmpArray actually contains objects in before attempting to grab its value...
e.g.
if ([tempArray count] >= 2) {
// do the above...
}

How to print a single array element in Objective-C?

How to print a array element at particular index in Objective-C? My code looks like this:
NSString *String=[NSString StringWithContentsOFFile:#"/User/Home/myFile.doc"];
NSString *separator = #"\n";
NSArray *array = [String componetntsSeparatedByString:separator];
NSLog(#"%#",array);
I'm able to print the full contents of an array at once, but I want to assign the element at each index into a string, like...
str1=array[0];
str2=array[1];
str3=array[0];...this continues
How do I do this?
You want the objectAtIndex: method. Example:
NSString *str1 = [array objectAtIndex:0];
NSString *str2 = [array objectAtIndex:1];
NSString *str3 = [array objectAtIndex:2];
From the documentation:
objectAtIndex:
Returns the object located at index.
- (id)objectAtIndex:(NSUInteger)index
Parameters
index
An index within the bounds of the receiver.
Return Value
The object located at index.
Discussion
If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.
if this is only for debugging, you could try using po <> in the gdb.
As of clang version 3.3, you can use the [index] notation, so
NSString *str1 = array[0];
would work now. See here for details.

Getting the string value from a NSArray

I have a NSArrayController and I when I get the selectedObjects and create a NSString with the value of valueForKey:#"Name" it returns
(
"This is still a work in progress "
)
and all I want to have is the text in the "" how would I get that? also, this my code:
NSArray *arrayWithSelectedObjects = [[NSArray alloc] initWithArray:[arrayController selectedObjects]];
NSString *nameFromArray = [NSString stringWithFormat:#"%#", [arrayWithSelectedObjects valueForKey:#"Name"]];
NSLog(#"%#", nameFromArray);
Edit: I also have other strings in the array
When you call valueForKey: on an array, it calls valueForKey: on each of the elements contained in the array, and returns those values in a new array, substituting NSNull for any nil values. There's also no need to duplicate the selectedObjects array from the controller because it is immutable anyway.
If you have multiple objects in your array controller's selected objects, and you want to see the value of the name key of all items in the selected objects, simply do:
NSArray *names = [[arrayController selectedObjects] valueForKey:#"name"];
for (id name in names)
NSLog (#"%#", name);
Of course, you could print them all out at once if you did:
NSLog (#"%#", [[arrayController selectedObjects] valueForKey:#"name"]);
If there's only one element in the selectedObjects array, and you call valueForKey:, it will still return an array, but it will only contain the value of the key of the lone element in the array. You can reference this with lastObject.
NSString *theName = [[[arrayController selectedObjects] valueForKey:#"name"] lastObject];
NSLog (#"%#", theName);