Using Chat Application XMPPFramework Iam getting This Error - ios

Using Chat Application with XMPPFramework Iam getting This Error
Message SendButton Action as given below, plz help me if any one have idea then tell me plz..............
- (IBAction)sendAction:(id)sender
{
if([_chatTextField.text length] > 0)
{
NSString* po = getUser.ofUser;
bubbleTable.typingBubble = NSBubbleTypingTypeNobody;
NSBubbleData *messageBubble = [NSBubbleData dataWithText:_chatTextField.text date:[NSDate dateWithTimeIntervalSinceNow:0] type:BubbleTypeMine];
[bubbleData addObject:messageBubble];
[bubbleTable reloadData];
[bubbleTable scrollBubbleViewToBottomAnimated:YES];
[[QuoteMessageController SharedInstance] SendChatMessageTo:getUser.account withContent:_chatTextField.text toUserId:[NSString stringWithFormat:#"%ld", (long)getUser.Id] andOFId:po andVerifyKey:chatMessageKey];
}
Getting error in output as given bellow>>>>>>
*** First throw call stack:
(
0 CoreFoundation 0x000000010e18ff35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010da7bbb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010e18fe6d +[NSException raise:format:] + 205
3 Foundation 0x000000010ba211f8 -[NSString stringByAppendingString:] + 96
4 SourceSage 0x000000010ae0c939 +[SSWriteReadInDb writeQuotesTable:UserImageUrl:UserId:OfUser:] + 409
5 SourceSage 0x000000010adb8d56 -[QuoteMessageController SendChatMessageTo:withContent:toUserId:andOFId:andVerifyKey:] + 2454
6 SourceSage 0x000000010ad6ac30 -[SSChatViewController sendAction:] + 752
7 UIKit 0x000000010beb48be -[UIApplication sendAction:to:from:forEvent:] + 75
8 UIKit 0x000000010bfbb410 -[UIControl _sendActionsForEvents:withEvent:] + 467
9 UIKit 0x000000010bfba7df -[UIControl touchesEnded:withEvent:] + 522
10 UIKit 0x000000010befa308 -[UIWindow _sendTouchesForEvent:] + 735
11 UIKit 0x000000010befac33 -[UIWindow sendEvent:] + 683
12 UIKit 0x000000010bec79b1 -[UIApplication sendEvent:] + 246
13 UIKit 0x000000010bed4a7d _UIApplicationHandleEventFromQueueEvent + 17370
14 UIKit 0x000000010beb0103 _UIApplicationHandleEventQueue + 1961
15 CoreFoundation 0x000000010e0c5551 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
16 CoreFoundation 0x000000010e0bb41d __CFRunLoopDoSources0 + 269
17 CoreFoundation 0x000000010e0baa54 __CFRunLoopRun + 868
18 CoreFoundation 0x000000010e0ba486 CFRunLoopRunSpecific + 470
19 GraphicsServices 0x000000010fe7c9f0 GSEventRunModal + 161
20 UIKit 0x000000010beb3420 UIApplicationMain + 1282
21 SourceSage 0x000000010ae02893 main + 115
22 libdyld.dylib 0x000000010ee2e145 start + 1
23 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

After looking at this part of your stack trace:
2 CoreFoundation 0x000000010e18fe6d +[NSException raise:format:] + 205
3 Foundation 0x000000010ba211f8 -[NSString stringByAppendingString:] + 96
4 SourceSage 0x000000010ae0c939 +[SSWriteReadInDb writeQuotesTable:UserImageUrl:UserId:OfUser:] + 409
5 SourceSage 0x000000010adb8d56 -[QuoteMessageController SendChatMessageTo:withContent:toUserId:andOFId:andVerifyKey:] + 2454
6 SourceSage 0x000000010ad6ac30 -[SSChatViewController sendAction:] + 752
You'll see the exception is raised after a string is appended to a string. That is usually caused from appending nil to the string. By guess is that one of your NSString arguments that you're sending to the method below is nil.
[[QuoteMessageController SharedInstance] SendChatMessageTo:getUser.account
withContent:_chatTextField.text
toUserId:[NSString stringWithFormat:#"%ld", (long)getUser.Id]
andOFId:po
andVerifyKey:chatMessageKey];
To find out if this is in fact the case, either set a breakpoint here and check all the values, or add in the following before you call this method:
NSLog(#"%#", getUser.account);
NSLog(#"%#", _chatTextField.text);
NSLog(#"%#", po);
NSLog(#"%#", [NSString stringWithFormat:#"%ld", (long)getUser.Id]);
NSLog(#"%#", chatMessageKey);
I don't know what your parameters actually are, so remove the NSLogs for the variables that are not NSString. If one of these logs come back as nil or null (I forget what the console will output), then you found your issue. If it's an argument that you don't necessarily need, you should pass an empty NSString instead. I usually do this with a ternary. So assuming the culprit is _chatTextField.text, I would pass that argument as:
[[QuoteMessageController SharedInstance] SendChatMessageTo:getUser.account
withContent:_chatTextField.text ?: #""
toUserId:[NSString stringWithFormat:#"%ld", (long)getUser.Id]
andOFId:po
andVerifyKey:chatMessageKey];
Doing this basically says, if _chatTextField.text is true (which it will equate to if it is not nill), use that value, otherwise use #""
EDIT:
- (IBAction)sendAction:(id)sender
{
if([_chatTextField.text length] > 0)
{
NSString* po = getUser.ofUser ?: #"";
NSString *acct = getUser.account ?: #"";
bubbleTable.typingBubble = NSBubbleTypingTypeNobody;
NSBubbleData *messageBubble = [NSBubbleData dataWithText:_chatTextField.text date:[NSDate dateWithTimeIntervalSinceNow:0] type:BubbleTypeMine];
[bubbleData addObject:messageBubble];
[bubbleTable reloadData];
[bubbleTable scrollBubbleViewToBottomAnimated:YES];
[[QuoteMessageController SharedInstance] SendChatMessageTo:acct withContent:_chatTextField.text toUserId:[NSString stringWithFormat:#"%ld", (long)getUser.Id] andOFId:po andVerifyKey:chatMessageKey];
}

Related

mutating method sent to immutable object'

I am trying to add object to the array from a dictionary . In else part I am getting this error
mutating method sent to immutable object'
NSMutableDictionary *selectedDict = [NSMutableDictionary new];
[selectedDict setObject:editedLineItem forKey:#"Text"];
[selectedDict setObject:#"fa-check" forKey:#"IconClass"];
NSMutableArray *tagListDictionary = [NSMutableArray new];
[tagListDictionary addObject:selectedTagsArray];
LineItemsStorage *linestorage = [LineItemsStorage sharedManager];
if(![linestorage.packagesArray valueForKey:#"Id"])
{
[linestorage.selectedLineItemsAndTagsArray addObject:selectedDict];
}
else{ [[linestorage.packagesArray valueForKey:#"LineItems"]addObject:[NSMutableArray arrayWithObject:selectedDict]];
}
-[NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'
*** First throw call stack:
(
0 CoreFoundation 0x00000001154a1d85 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000114f15deb objc_exception_throw + 48
2 CoreFoundation 0x00000001154a1cbd +[NSException raise:format:] + 205
3 CoreFoundation 0x0000000115497b0a -[__NSCFArray insertObject:atIndex:] + 106
4 FlatPebble 0x000000010f276014 -[LineItemViewController okayAction] + 836
5 UIKit 0x0000000113809a8d -[UIApplication sendAction:to:from:forEvent:] + 92
6 UIKit 0x000000011397ce67 -[UIControl sendAction:to:forEvent:] + 67
7 UIKit 0x000000011397d143 -[UIControl _sendActionsForEvents:withEvent:] + 327
8 UIKit 0x000000011397c263 -[UIControl touchesEnded:withEvent:] + 601
9 UIKit 0x000000011387c99f -[UIWindow _sendTouchesForEvent:] + 835
10 UIKit 0x000000011387d6d4 -[UIWindow sendEvent:] + 865
11 UIKit 0x0000000113828dc6 -[UIApplication sendEvent:] + 263
12 UIKit 0x0000000113802553 _UIApplicationHandleEventQueue + 6660
13 CoreFoundation 0x00000001153c7301 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17
14 CoreFoundation 0x00000001153bd22c __CFRunLoopDoSources0 + 556
15 CoreFoundation 0x00000001153bc6e3 __CFRunLoopRun + 867
16 CoreFoundation 0x00000001153bc0f8 CFRunLoopRunSpecific + 488
17 GraphicsServices 0x0000000116e5cad2 GSEventRunModal + 161
18 UIKit 0x0000000113807f09 UIApplicationMain + 171
19 *********** 0x000000010f348c2f main + 111
20 libdyld.dylib 0x0000000115d9992d start + 1
)
Use this code
NSMutableDictionary *selectedDict = [[NSMutableDictionary new]mutableCopy];
[selectedDict setObject:editedLineItem forKey:#"Text"];
[selectedDict setObject:#"fa-check" forKey:#"IconClass"];
NSMutableArray *tagListDictionary = [[NSMutableArray new]mutableCopy];
[tagListDictionary addObject:selectedTagsArray];
LineItemsStorage *linestorage = [LineItemsStorage sharedManager];
if(![linestorage.packagesArray valueForKey:#"Id"])
{
[linestorage.selectedLineItemsAndTagsArray addObject:selectedDict];
}
else{ [[linestorage.packagesArray valueForKey:#"LineItems"]addObject:[NSMutableArray arrayWithObject:selectedDict]];
}
Assuming your packagesArray contains an array containing one or more objects that have a LineItems property (that happens to also be an array); your problem is here:
[[linestorage.packagesArray valueForKey:#"LineItems"]addObject:[NSMutableArray arrayWithObject:selectedDict]]
Breaking it down it is equivalent to:
NSArray* packagesLineItems = [linestorage.packagesArray valueForKey:#"LineItems"];
NSMutableArray* selected = [NSMutableArray arrayWithObject:selectedDict];
[packagesLineItems addObject:selected];
So your problem is either the return type of valueForKey (when called on an array), or the action you're trying to do on it.

Adding null object to SQLite

I implemented SQLite in xcode. I have 2 columns. When the first column has a row, then the second one is set to null, and vice versa. I'm trying to go through both columns and check if it has an object at that index.
NSLog(#"%# and %#", firstArray, secondArray); // It gives the right risults, but there aren't any null objects in any of them.
for (int i = 0; i < [firstArray count]; i++)
{
if (![[firstArray objectAtIndex:i] length] && [[secondArray objectAtIndex:i] length]) {
...
}
}
I have two issues.
First: There aren't any null objects in the rows, even though I set some to null. So what should I do to check if there is a null object, or if there's another way to add some kind null object that will actually add to the tables row?
Second: When I compile and run the app, it crashes with the error below. But when I remove the if statement, it works flawlessly.
-[__NSArrayM length]: unrecognized selector sent to instance 0x7fbfeb53b0a0
2015-03-30 11:25:04.731 MyApp [610:15600] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM length]: unrecognized selector sent to instance 0x7fbfeb53b0a0'
*** First throw call stack:
(
0 CoreFoundation 0x0000000110874f35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000011050dbb7 objc_exception_throw + 45
2 CoreFoundation 0x000000011087c04d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00000001107d427c ___forwarding___ + 988
4 CoreFoundation 0x00000001107d3e18 _CF_forwarding_prep_0 + 120
5 MyApp 0x000000010fec3b59 -[ViewController ingredientAction] + 889
6 MyApp 0x000000010feba253 -[ViewController menuAction:] + 195
7 UIKit 0x0000000110ea58be -[UIApplication sendAction:to:from:forEvent:] + 75
8 UIKit 0x0000000110fac410 -[UIControl _sendActionsForEvents:withEvent:] + 467
9 UIKit 0x00000001110269ea -[UISegmentedControl _setSelectedSegmentIndex:notify:animate:] + 570
10 UIKit 0x0000000111028a0f -[UISegmentedControl touchesEnded:withEvent:] + 143
11 UIKit 0x0000000111252540 _UIGestureRecognizerUpdate + 9487
12 UIKit 0x0000000110eeaff6 -[UIWindow _sendGesturesForEvent:] + 1041
13 UIKit 0x0000000110eebc23 -[UIWindow sendEvent:] + 667
14 UIKit 0x0000000110eb89b1 -[UIApplication sendEvent:] + 246
15 UIKit 0x0000000110ec5a7d _UIApplicationHandleEventFromQueueEvent + 17370
16 UIKit 0x0000000110ea1103 _UIApplicationHandleEventQueue + 1961
17 CoreFoundation 0x00000001107aa551 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
18 CoreFoundation 0x00000001107a041d __CFRunLoopDoSources0 + 269
19 CoreFoundation 0x000000011079fa54 __CFRunLoopRun + 868
20 CoreFoundation 0x000000011079f486 CFRunLoopRunSpecific + 470
21 GraphicsServices 0x0000000114c759f0 GSEventRunModal + 161
22 UIKit 0x0000000110ea4420 UIApplicationMain + 1282
23 MyApp 0x000000010fec11b3 main + 115
24 libdyld.dylib 0x00000001122ad145 start + 1
25 ??? 0x0000000000000001 0x0 + 1
Edit
I put #"" instead of null into the row. Then I change the if statement (in the for loop) to the following:
NSStirng *objectAtIndexFromArray = [NSString stringWithFormat:#"%#", [firstArray objectAtIndex:i]];
if ([objectAtIndexFromArray isEqualToString:#""])
{
NSLog(#"Hello");
}
I don't get any NSLogs of Hello.
I'm pretty new to ios development, but I know that if you want to add null object to you data collection you have to use NSNULL class.
NSArray can't hold nils, if you want to check if null, please use this code
id object = myArray[0];// similar to [myArray objectAtIndex:0]
if(![object isEqual:[NSNull null]])
{
//do something if object is not equals to [NSNull null]
}

How is my code producing this crash: [NSConcreteData count]: unrecognized selector sent to instance

I am getting this crash showing up in BugSense:
-[NSConcreteData count]: unrecognized selector sent to instance 0x14e57f10 - NSInvalidArgumentException
in this code:
+ (NSMutableArray *)applyFilters:(NSMutableArray *)theItems fromFilter:(NSDictionary *)filters
{
NSMutableArray *items = [[NSMutableArray alloc] initWithArray:theItems];
if ([[filters allKeys] count] > 0)
{
NSMutableArray *tempFilteredItems = [[NSMutableArray alloc] init];
for (NSString *key in [filters allKeys])
{
NSMutableString *convertedKey = [NSMutableString stringWithString:key];
[convertedKey replaceOccurrencesOfString:#" "
withString:#"_"
options:NSCaseInsensitiveSearch
range:NSMakeRange(0, [convertedKey length])];
NSArray *tempFilterAttributes = [NSArray arrayWithArray:filters[key]];
for (NSDictionary *item in items)
{
if (![[item[convertedKey] componentsSeparatedByString:#"*"] firstObjectCommonWithArray:tempFilterAttributes])
{
if (![tempFilteredItems containsObject:item])
{
[tempFilteredItems addObject:item];
}
}
}
[items removeObjectsInArray:tempFilteredItems];
[tempFilteredItems removeAllObjects];
}
}
return items;
}
Why/how is this happening?
Stack trace is:
CoreFoundation <redacted> + 130
1 libobjc.A.dylib objc_exception_throw + 38
2 CoreFoundation <redacted> + 202
3 CoreFoundation <redacted> + 706
4 CoreFoundation _CF_forwarding_prep_0 + 24
5 CoreFoundation <redacted> + 28
6 Video Games +[Helper applyFilters:fromFilter:] (Helper.m:2862)
7 Video Games -[WishlistViewController loadUp] (WishlistViewController.m:409) + 29303
8 Video Games -[WishlistViewController viewWillAppear:] (WishlistViewController.m:363) + 27955
9 UIKit <redacted> + 374
10 UIKit <redacted> + 612
11 UIKit <redacted> + 572
12 UIKit <redacted> + 44
13 UIKit <redacted> + 184
14 UIKit <redacted> + 380
15 QuartzCore <redacted> + 142
16 QuartzCore <redacted> + 350
17 QuartzCore <redacted> + 16
18 QuartzCore <redacted> + 228
19 QuartzCore <redacted> + 314
20 UIKit <redacted> + 126
21 CoreFoundation <redacted> + 20
22 CoreFoundation <redacted> + 286
23 CoreFoundation <redacted> + 738
24 CoreFoundation CFRunLoopRunSpecific + 524
25 CoreFoundation CFRunLoopRunInMode + 106
26 GraphicsServices GSEventRunModal + 138
27 UIKit UIApplicationMain + 1136
28 Video Games main (main.m:16) + 888911
29 libdyld.dylib <redacted> + 2
The problem has nothing to do with the code that you provided. The error messages says that the message count was sent to the class NSConcreteData, which is essentially the same as NSData, and such a class method does not exist.
I suggest that you set an exception breakpoint (in Xcode select left the breakpoint navigator, click + left bottom, and select add exception breakpoint).
When you execute the app, it will stop at the faulty instruction.
EDIT (due to the stack trace you provided now):
The stack trace indeed says that your method applyFilters:fromFilter: is responsible for the crash. The only place where the message count is sent in this method, is the statement [[filters allKeys] count]. It looks then that count is sent to an NSConcreteData object, and not to an NSArray object as you might have expected. One reason could be that the argument filters, that should be a NSDictionary, is an object of a different type.
So when the app stops at the exception breakpoint, please check the class of the instance filters.

Add empty object to an array

I need to add an empty object to index 0 and index 1 of an array being populated with data from a third party XML feed.
This is my parseXML method, it works.
-(void) parseXML{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"APIKEYHERECANTSHOW YOU"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *xmlString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"The string : %#", xmlString);
NSDictionary *xml = [NSDictionary dictionaryWithXMLString:xmlString];
NSLog(#"The dict:%#", xml);
NSMutableDictionary *PageItem = [xml objectForKey:#"TeamLeagueStanding"];
NSLog(#"PageItem: %#", PageItem);
NSMutableArray *items = [xml objectForKey:#"TeamLeagueStanding"];
NSNull *nullValue = [NSNull null];
[items insertObject:nullValue atIndex:0]; <- THIS MAKES MY APP CRASH
NSLog(#"The array: %#", items);
[self setTableData:items];
}
But when i run this i get a crash with the console output:
2014-02-03 21:24:09.063 Liga Zon Sagres Companion[9645:70b] -[NSNull objectForKey:]: unrecognized selector sent to instance 0x101a85b40
2014-02-03 21:24:09.066 Liga Zon Sagres Companion[9645:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull objectForKey:]: unrecognized selector sent to instance 0x101a85b40'
*** First throw call stack:
(
0 CoreFoundation 0x000000010192a795 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010168d991 objc_exception_throw + 43
2 CoreFoundation 0x00000001019bbbad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x000000010191c09d ___forwarding___ + 973
4 CoreFoundation 0x000000010191bc48 _CF_forwarding_prep_0 + 120
5 Liga Zon Sagres Companion 0x000000010000ee20 -[StandingsTableViewController tableView:cellForRowAtIndexPath:] + 256
6 UIKit 0x00000001003bbb8a -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 348
7 UIKit 0x00000001003a3836 -[UITableView _updateVisibleCellsNow:] + 2297
8 UIKit 0x00000001003b4381 -[UITableView layoutSubviews] + 207
9 UIKit 0x000000010034bb27 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 354
10 QuartzCore 0x0000000102081a22 -[CALayer layoutSublayers] + 151
11 QuartzCore 0x0000000102076589 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 363
12 QuartzCore 0x0000000102081956 -[CALayer layoutIfNeeded] + 162
13 UIKit 0x00000001003ebfc2 -[UIViewController window:setupWithInterfaceOrientation:] + 264
14 UIKit 0x000000010032ab4d -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:isRotating:] + 4360
15 UIKit 0x0000000100329a3f -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:] + 36
16 UIKit 0x000000010032998f -[UIWindow _setRotatableViewOrientation:updateStatusBar:duration:force:] + 101
17 UIKit 0x0000000100328c9e -[UIWindow _updateToInterfaceOrientation:duration:force:] + 377
18 UIKit 0x00000001003dfd4a -[UIViewController _tryBecomeRootViewControllerInWindow:] + 147
19 UIKit 0x0000000100323a87 -[UIWindow addRootViewControllerViewIfPossible] + 506
20 UIKit 0x0000000100323bd5 -[UIWindow _setHidden:forced:] + 275
21 UIKit 0x000000010032cca2 -[UIWindow makeKeyAndVisible] + 51
22 UIKit 0x00000001002eb0c8 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1449
23 UIKit 0x00000001002eebe8 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 660
24 UIKit 0x00000001002ffaab -[UIApplication handleEvent:withNewEvent:] + 3092
25 UIKit 0x00000001002fff1e -[UIApplication sendEvent:] + 79
26 UIKit 0x00000001002f02be _UIApplicationHandleEvent + 618
27 GraphicsServices 0x0000000102578bb6 _PurpleEventCallback + 762
28 GraphicsServices 0x000000010257867d PurpleEventCallback + 35
29 CoreFoundation 0x00000001018ac819 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
30 CoreFoundation 0x00000001018ac5ee __CFRunLoopDoSource1 + 478
31 CoreFoundation 0x00000001018d5ab3 __CFRunLoopRun + 1939
32 CoreFoundation 0x00000001018d4f33 CFRunLoopRunSpecific + 467
33 UIKit 0x00000001002ee4bd -[UIApplication _run] + 609
34 UIKit 0x00000001002f0043 UIApplicationMain + 1010
35 Liga Zon Sagres Companion 0x0000000100011f93 main + 115
36 libdyld.dylib 0x0000000102f815fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Any ideas how to solve this? Thank you.
The error is coming from your StandingsTableViewController tableView:cellForRowAtIndexPath: method. Your data is giving you an NSNull instance where you expect an NSDictionary.
Since you explicitly add the NSNull object you need to update your cellForRow... method to check to see if the object is an NSNull instance before assuming it is an NSDictionary.
Something like this:
NSDictionary *data = self.tableData[someIndex];
if ([data isKindOfClass:[NSDictionary class]]) {
// process the data as usual
} else {
// This is probably the NSNull object, ignore it or handle appropriately
}

Xcode: App crashes because I deleted a class no other class uses anymore?

Very strange behaviour...I've used before an NSNumber category called NSNumber+Currencies. Yesterday I've changed everything including core data to NSDecimalNumber so I have now a class NSDecimalNumber+Currencies. There is really no link at all! to NSNumber+Currencies anymore. However if I delete it and try to run my app in the simulator, my app crashes with the message "unrecognized selector sent to instance ..." This instance is a NSDecimalNumber and the methods I use in this category are basically the same as before. And I really import ONLY the NSDecimalNumber+Currencies. But it makes no sense...I've deleted the app from the simulator, cleaned my project, closed Xcode, removed the old category even manually from the build phases but nothing helps..is there another trick? If I leave this old category in it it runs smoothly...
My error log. However after the 2nd run my app doesn't start at all and the error message is a different one:
2014-01-28 11:51:29.458 NetIncome[2341:70b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(
0 CoreFoundation 0x01ecf5e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x01abe8b6 objc_exception_throw + 44
2 CoreFoundation 0x01e839c2 -[__NSArrayI objectAtIndex:] + 210
3 CoreData 0x01899c1f -[NSFetchedResultsController objectAtIndexPath:] + 255
4 NetIncome 0x00003dee -[MainCategoriesViewController tableView:cellForRowAtIndexPath:] + 206
5 UIKit 0x003ac61f -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 412
6 UIKit 0x003ac6f3 -[UITableView _createPreparedCellForGlobalRow:] + 69
7 UIKit 0x00390774 -[UITableView _updateVisibleCellsNow:] + 2378
8 UIKit 0x0038eb81 -[UITableView _updateVisibleCellsImmediatelyIfNecessary] + 66
9 UIKit 0x0039cb5f -[UITableView _visibleCells] + 35
10 UIKit 0x0039cbb4 -[UITableView visibleCells] + 33
11 UIKit 0x0039fcc0 -[UITableView setSeparatorStyle:] + 115
12 NetIncome 0x000037d4 -[MainCategoriesViewController styleTableView] + 100
13 NetIncome 0x0000300a -[MainCategoriesViewController viewDidLoad] + 1194
14 UIKit 0x003d1318 -[UIViewController loadViewIfRequired] + 696
15 UIKit 0x003f6b15 -[UINavigationController _layoutViewController:] + 39
16 UIKit 0x003f702b -[UINavigationController _updateScrollViewFromViewController:toViewController:] + 235
17 UIKit 0x003f7123 -[UINavigationController _startTransition:fromViewController:toViewController:] + 78
18 UIKit 0x003f809c -[UINavigationController _startDeferredTransitionIfNeeded:] + 645
19 UIKit 0x003f8cb9 -[UINavigationController __viewWillLayoutSubviews] + 57
20 UIKit 0x00532181 -[UILayoutContainerView layoutSubviews] + 213
21 UIKit 0x00328267 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
22 libobjc.A.dylib 0x01ad081f -[NSObject performSelector:withObject:] + 70
23 QuartzCore 0x001972ea -[CALayer layoutSublayers] + 148
24 QuartzCore 0x0018b0d4 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
25 QuartzCore 0x00197235 -[CALayer layoutIfNeeded] + 160
26 UIKit 0x003e3613 -[UIViewController window:setupWithInterfaceOrientation:] + 304
27 UIKit 0x00302177 -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:isRotating:] + 5212
28 UIKit 0x00300d16 -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:] + 82
29 UIKit 0x00300be8 -[UIWindow _setRotatableViewOrientation:updateStatusBar:duration:force:] + 117
30 UIKit 0x00300c70 -[UIWindow _setRotatableViewOrientation:duration:force:] + 67
31 UIKit 0x002ffd0a __57-[UIWindow _updateToInterfaceOrientation:duration:force:]_block_invoke + 120
32 UIKit 0x002ffc6c -[UIWindow _updateToInterfaceOrientation:duration:force:] + 400
33 UIKit 0x003009c3 -[UIWindow setAutorotates:forceUpdateInterfaceOrientation:] + 870
34 UIKit 0x00303fb6 -[UIWindow setDelegate:] + 449
35 UIKit 0x003d5737 -[UIViewController _tryBecomeRootViewControllerInWindow:] + 180
36 UIKit 0x002f9c1c -[UIWindow addRootViewControllerViewIfPossible] + 609
37 UIKit 0x002f9d97 -[UIWindow _setHidden:forced:] + 312
38 UIKit 0x002fa02d -[UIWindow _orderFrontWithoutMakingKey] + 49
39 UIKit 0x0030489a -[UIWindow makeKeyAndVisible] + 65
40 UIKit 0x002b7cd0 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1851
41 UIKit 0x002bc3a8 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 824
42 UIKit 0x002d087c -[UIApplication handleEvent:withNewEvent:] + 3447
43 UIKit 0x002d0de9 -[UIApplication sendEvent:] + 85
44 UIKit 0x002be025 _UIApplicationHandleEvent + 736
45 GraphicsServices 0x035202f6 _PurpleEventCallback + 776
46 GraphicsServices 0x0351fe01 PurpleEventCallback + 46
47 CoreFoundation 0x01e4ad65 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
48 CoreFoundation 0x01e4aa9b __CFRunLoopDoSource1 + 523
49 CoreFoundation 0x01e7577c __CFRunLoopRun + 2156
50 CoreFoundation 0x01e74ac3 CFRunLoopRunSpecific + 467
51 CoreFoundation 0x01e748db CFRunLoopRunInMode + 123
52 UIKit 0x002bbadd -[UIApplication _run] + 840
53 UIKit 0x002bdd3b UIApplicationMain + 1225
54 NetIncome 0x000027ad main + 141
55 libdyld.dylib 0x031c070d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
EDIT2: And this is the original error message, only shown once and immediately after deleting the relevant files:
2014-01-28 12:00:15.598 NetIncome[2872:70b] -[__NSCFNumber getLocalizedCurrencyString]: unrecognized selector sent to instance 0x8c59720
2014-01-28 12:00:15.602 NetIncome[2872:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber getLocalizedCurrencyString]: unrecognized selector sent to instance 0x8c59720'
*** First throw call stack:
(
0 CoreFoundation 0x01ecf5e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x01abe8b6 objc_exception_throw + 44
2 CoreFoundation 0x01f6c903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x01ebf90b ___forwarding___ + 1019
4 CoreFoundation 0x01ebf4ee _CF_forwarding_prep_0 + 14
5 NetIncome 0x000358da -[NetIncomeViewController viewDidLoad] + 954
6 UIKit 0x003d1318 -[UIViewController loadViewIfRequired] + 696
7 UIKit 0x003f6b15 -[UINavigationController _layoutViewController:] + 39
8 UIKit 0x003f702b -[UINavigationController _updateScrollViewFromViewController:toViewController:] + 235
9 UIKit 0x003f7123 -[UINavigationController _startTransition:fromViewController:toViewController:] + 78
10 UIKit 0x003f809c -[UINavigationController _startDeferredTransitionIfNeeded:] + 645
11 UIKit 0x003f8cb9 -[UINavigationController __viewWillLayoutSubviews] + 57
12 UIKit 0x00532181 -[UILayoutContainerView layoutSubviews] + 213
13 UIKit 0x00328267 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
14 libobjc.A.dylib 0x01ad081f -[NSObject performSelector:withObject:] + 70
15 QuartzCore 0x001972ea -[CALayer layoutSublayers] + 148
16 QuartzCore 0x0018b0d4 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
17 QuartzCore 0x0018af40 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
18 QuartzCore 0x000f2ae6 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
19 QuartzCore 0x000f3e71 _ZN2CA11Transaction6commitEv + 393
20 QuartzCore 0x001b0430 +[CATransaction flush] + 52
21 UIKit 0x002d9dc9 _afterCACommitHandler + 131
22 CoreFoundation 0x01e974ce __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
23 CoreFoundation 0x01e9741f __CFRunLoopDoObservers + 399
24 CoreFoundation 0x01e75344 __CFRunLoopRun + 1076
25 CoreFoundation 0x01e74ac3 CFRunLoopRunSpecific + 467
26 CoreFoundation 0x01e748db CFRunLoopRunInMode + 123
27 GraphicsServices 0x0351e9e2 GSEventRunModal + 192
28 GraphicsServices 0x0351e809 GSEventRun + 104
29 UIKit 0x002bdd3b UIApplicationMain + 1225
30 NetIncome 0x00002b3d main + 141
31 libdyld.dylib 0x031c070d start + 1
32 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
The lines of code my app crashes the first time (the last line is the one):
//Get or set and get the gross income
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDecimalNumber *grossIncome = [defaults objectForKey:#"grossincome"];
if (!grossIncome) {
[defaults setObject:[NSDecimalNumber zero] forKey:#"grossincome"];
[defaults synchronize];
grossIncome = (NSDecimalNumber *)[defaults objectForKey:#"grossincome"];
}
self.incomeValueTextField.enabled = NO;
self.incomeValueTextField.delegate = self;
self.incomeValueTextField.keyboardType = UIKeyboardTypeDecimalPad;
self.incomeValueTextField.text = [grossIncome getLocalizedCurrencyString];
And my complete category:
#import "NSDecimalNumber+Currency.h"
#import "Singletons.h"
#implementation NSDecimalNumber (Currency)
- (NSString *) getLocalizedCurrencyString
{
NSNumberFormatter *numberFormatter = [[Singletons sharedManager] numberFormatter];
NSString *numberString = [numberFormatter stringFromNumber:self];
return numberString;
}
- (NSString *) getLocalizedCurrencyStringWithDigits:(int)digits
{
if(digits == 2){
return [self getLocalizedCurrencyString];
}
NSNumberFormatter *numberFormatter;
if (digits == 0){
numberFormatter =[[Singletons sharedManager] numberFormatterNoDigits];
} else {
numberFormatter =[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setMinimumFractionDigits:digits];
[numberFormatter setMaximumFractionDigits:digits];
}
NSString *numberString = [numberFormatter stringFromNumber:self];
return numberString;
}
+ (NSDecimalNumber *) getUnLocalizedDecimalNumberWithString:(NSString *)currencyString
{
NSNumberFormatter *numberFormatter = [[Singletons sharedManager] numberFormatter];
NSNumber *formatedCurrency = [numberFormatter numberFromString:currencyString];
BOOL isDecimal = formatedCurrency != nil;
if(isDecimal){
return [NSDecimalNumber decimalNumberWithDecimal:[formatedCurrency decimalValue]];
} else {
return [NSDecimalNumber zero];
}
}
- (NSDecimalNumber *)abs {
if ([self compare:[NSDecimalNumber zero]] == NSOrderedAscending) {
// Number is negative. Multiply by -1
NSDecimalNumber * negativeOne = [NSDecimalNumber decimalNumberWithMantissa:1
exponent:0
isNegative:YES];
return [self decimalNumberByMultiplyingBy:negativeOne];
} else {
return self;
}
}
Yesterday you have been warned about subclassing/categories on class clusters, now you see why. (Okay, actually it's more or a problem with unexpected behaviour of NSUserDefaults, but it's related ^^)
Your problem is that the object you get from NSUserDefaults is not a NSDecimalNumber, because NSDecimalNumbers are not plist values that can be saved in NSUserDefaults. But NSDecimalNumber is a subclass of NSNumber, which can be saved in NSUserDefaults, so NSUserDefaults will only save the "NSNumber part" of the NSDecimalNumber, basically it converts it to a NSNumber. Through this process it loses its precision and it's class.
When you get the object from NSUserDefaults you will actually get an instance of NSNumber. And your category does not exist on NSNumber.
I added some debug log to your code and ran it for you:
// Wrong!
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:#"1.23456789123456789"];
NSLog(#"%# - %#", decimalNumber, NSStringFromClass([decimalNumber class]));
[[NSUserDefaults standardUserDefaults] setObject:decimalNumber forKey:#"___number"];
NSDecimalNumber *objectFromUserDefaults = [[NSUserDefaults standardUserDefaults] objectForKey:#"___number"];
NSLog(#"%# - %#", objectFromUserDefaults, NSStringFromClass([objectFromUserDefaults class]));
Which yields this result:
xxx[98912:70b] 1.23456789123456789 - NSDecimalNumber
xxx[98912:70b] 1.234567891234568 - __NSCFNumber
As you can see the returned object is an instance of __NSCFNumber
Here is the correct way:
// Correct
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:#"1.23456789123456789"];
NSLog(#"%# - %#", decimalNumber, NSStringFromClass([decimalNumber class]));
NSData *archivedDecimalNumber = [NSKeyedArchiver archivedDataWithRootObject:decimalNumber];
[[NSUserDefaults standardUserDefaults] setObject:archivedDecimalNumber forKey:#"___archivedNumber"];
NSData *dataFromUserDefaults = [[NSUserDefaults standardUserDefaults] objectForKey:#"___archivedNumber"];
NSDecimalNumber *decimalNumberFromUserDefaults = [NSKeyedUnarchiver unarchiveObjectWithData:dataFromUserDefaults];
NSLog(#"%# - %#", decimalNumberFromUserDefaults, NSStringFromClass([decimalNumberFromUserDefaults class]));
which yields:
xxx[98912:70b] 1.23456789123456789 - NSDecimalNumber
xxx[98912:70b] 1.23456789123456789 - NSDecimalNumber
as expected.
BUT you should still get rid of that NSDecimalNumber category. Just put that code into it's own class. Call it ZHNumberFormatter and do your formatting in there.
NSNumberFormatters take their time during creation, you don't want to create them for every single conversion.
Reset your simulator and try to run the app.
iOS Simulator --> Reset content and settings.
User NSKeyedArchiver and NSKeyedUnarchiver to store the object in user defaults.
Try to use below code its working fine.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDecimalNumber *grossIncome = [defaults objectForKey:#"grossincome"];
if (!grossIncome) {
NSDecimalNumber *decNum = [[NSDecimalNumber alloc] initWithDouble:0.0f];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:decNum];
[defaults setObject:myEncodedObject forKey:#"grossincome"];
[defaults synchronize];
NSData *myDecodedObject = [defaults objectForKey:#"grossincome"];
grossIncome = (NSDecimalNumber*)[NSKeyedUnarchiver unarchiveObjectWithData:myDecodedObject];
}
[grossIncome getLocalizedCurrencyString];
You probably still refer to the category somewhere.
You should create an exception Breakpoint. (look for "create exception Breakpoint" in the help menu)
This will stop you on the guilty line of code!

Resources