I am creating one app in which I am saving my array of custom object in NSUserDefaults using this below code :
[Util setSubProductsArrayPreference:myArray forKey:productId];
//Util.m
+(void)setSubProductsArrayPreference:(NSMutableArray *)subProducts forKey:(NSString *)string
{
for (int i=0; i<subProducts.count; i++) {
SubProducts *po=[subProducts objectAtIndex:i];
NSString *st=[NSString stringWithFormat:#"%d",i];
[Util setSubProductsPreference:po forKey:st];
}
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:subProducts];
[prefs setObject:myEncodedObject forKey:string];
[prefs synchronize];
}
+(void)setSubProductsPreference:(SubProducts *)subProducts forKey:(NSString *)key
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:subProducts];
[prefs setObject:myEncodedObject forKey:key];//here it is crashing
[prefs synchronize];
}
This code is working fine with iOS7 and prior..The problem is when I am running my same code with iOS8 in xCode6 then I am getting the below error :
-[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000f23
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000f23'
*** First throw call stack:
(
0 CoreFoundation 0x00000001042fbf35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000103bbabb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010430304d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x000000010425b27c ___forwarding___ + 988
4 CoreFoundation 0x000000010425ae18 _CF_forwarding_prep_0 + 120
5 CoreFoundation 0x00000001042bc790 _CFPrefsEncodeKeyValuePairIntoMessage + 64
6 CoreFoundation 0x00000001042fe286 -[CFPrefsPlistSource sendMessageSettingValue:forKey:] + 102
7 CoreFoundation 0x000000010423cef7 -[CFPrefsPlistSource alreadylocked_setValue:forKey:] + 215
8 CoreFoundation 0x000000010423cdee -[CFPrefsSource setValue:forKey:] + 62
9 CoreFoundation 0x00000001041fa1f8 +[CFPrefsSource withSourceForIdentifier:user:byHost:container:perform:] + 1112
10 CoreFoundation 0x000000010423cd63 _CFPreferencesSetValueWithContainer + 227
11 Foundation 0x000000010374099b -[NSUserDefaults(NSUserDefaults) setObject:forKey:] + 46
12 HP ProTrain 0x0000000101186787 +[Util setSubProductsArrayPreference:forKey:] + 487
13 HP ProTrain 0x0000000101115a38 __74-[DesktopProductsViewController fetchingProductSubCategoryDataFromServer:]_block_invoke_2 + 3096
14 libdispatch.dylib 0x00000001051b4ba6 _dispatch_call_block_and_release + 12
15 libdispatch.dylib 0x00000001051d27f4 _dispatch_client_callout + 8
16 libdispatch.dylib 0x00000001051bb8fb _dispatch_main_queue_callback_4CF + 949
17 CoreFoundation 0x0000000104263fe9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
18 CoreFoundation 0x0000000104226eeb __CFRunLoopRun + 2043
19 CoreFoundation 0x0000000104226486 CFRunLoopRunSpecific + 470
20 GraphicsServices 0x00000001082c29f0 GSEventRunModal + 161
21 UIKit 0x0000000102463420 UIApplicationMain + 1282
22 HP ProTrain 0x00000001010c1a87 main + 151
23 libdyld.dylib 0x0000000105207145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Do any one else experience the same problem?
Change this line
[Util setSubProductsArrayPreference:myArray forKey:[NSString stringWithFormat:#"%#",productId]];
Simple, your productId is not returning string. Just typecast productId to NSString before setObject.
Related
I have a custom class oject that I want to save using NSUserDefaults, this is how I saving it:
Shift.m
-(void)encodeWithCoder:(NSCoder*)encoder
{
[encoder encodeObject:self.date forKey:#"date"];
[encoder encodeObject:self.startTime forKey:#"startTime"];
[encoder encodeObject:self.endTime forKey:#"endTime"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if(self = [super init]) {
self.date = [decoder decodeObjectForKey:#"date"];
self.startTime = [decoder decodeObjectForKey:#"startTime"];
self.endTime = [decoder decodeObjectForKey:#"endTime"];
}
return self;
}
MyTableViewController.m:
-(void)saveCustomObject:(id)object forKey:(NSString*)key
{
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[[NSUserDefaults standardUserDefaults] setObject:encodedObject forKey:key];
}
-(NSArray*)getCustomObjectForKey:(NSString*)key
{
NSData *encodedObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
NSArray *shifts=[NSArray arrayWithObjects:[NSKeyedUnarchiver unarchiveObjectWithData:encodedObject], nil];
return shifts;
}
It seems it works fine when debugging, but when I try to access one of the object properties, for example on tableView: cellForRowAtIndexPath: like that:
Shift *currentShift=[self.shifts objectForIndex:indexPath.row];
NSLog(#"%#",currentShift.startTime.description);
It crashes with that crash message:
2016-03-19 09:04:05.913 MyApp[9654:4249448] -[__NSArrayM startTime]: unrecognized selector sent to instance 0x7ff81b449c10
2016-03-19 09:04:05.924 MyApp[9654:4249448] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM startTime]: unrecognized selector sent to instance 0x7ff81b449c10'
*** First throw call stack:
(
0 CoreFoundation 0x000000010e3e9e65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010de62deb objc_exception_throw + 48
2 CoreFoundation 0x000000010e3f248d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x000000010e33f90a ___forwarding___ + 970
4 CoreFoundation 0x000000010e33f4b8 _CF_forwarding_prep_0 + 120
5 Mehuyavut count 0x000000010d95a8e8 -[shiftsTableViewViewController tableView:cellForRowAtIndexPath:] + 600
6 UIKit 0x000000010e8efe43 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 766
7 UIKit 0x000000010e8eff7b -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
8 UIKit 0x000000010e8c4a39 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2996
9 UIKit 0x000000010e8f901c -[UITableView _performWithCachedTraitCollection:] + 92
10 UIKit 0x000000010e8dfedc -[UITableView layoutSubviews] + 224
11 UIKit 0x000000010e84d4a3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 703
12 QuartzCore 0x000000011231959a -[CALayer layoutSublayers] + 146
13 QuartzCore 0x000000011230de70 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
14 QuartzCore 0x000000011230dcee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
15 QuartzCore 0x0000000112302475 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277
16 QuartzCore 0x000000011232fc0a _ZN2CA11Transaction6commitEv + 486
17 QuartzCore 0x000000011233037c _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
18 CoreFoundation 0x000000010e315367 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
19 CoreFoundation 0x000000010e3152d7 __CFRunLoopDoObservers + 391
20 CoreFoundation 0x000000010e30af2b __CFRunLoopRun + 1147
21 CoreFoundation 0x000000010e30a828 CFRunLoopRunSpecific + 488
22 GraphicsServices 0x0000000111ba6ad2 GSEventRunModal + 161
23 UIKit 0x000000010e796610 UIApplicationMain + 171
24 Mehuyavut count 0x000000010d95b5af main + 111
25 libdyld.dylib 0x0000000110b2592d start + 1
26 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Any one knows why?
Thank you!
It seems like you want Shift *currentShift=[self.shifts objectForIndex:indexPath.row] to give you 1 Shift object, but what it really does is returning a NSArray. You basically call a startTime method in NSArray, and since it doesn't exist, your program fails.
It seems like NSLog(#"%#",currentShift.startTime.description) is the line doing that. Confirm by commenting out the NSLog. It shouldn't give you a crash.
If this hypothesis is fine, check if [currentShift isKindOfClass:[NSArray class]] is true.
If it is, a bug you have in this line:
NSArray *shifts=[NSArray arrayWithObjects:[NSKeyedUnarchiver unarchiveObjectWithData:encodedObject], nil];
You also don't really show how your - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section looks like. You must return proper number of entries there.
You're making self.shifts be an NSArray, but you use objectForKey, which is available for dictionaries. It's not available for arrays. I think you wanted objectAtIndex instead.
I want to make a new object from string access_token.
I've made a Token:NSObject (.h + .m) and I'm trying to setAccessToken and show it in the NSLog. This is the code in my LoginViewController.m:
NSString *token = responseObject[#"access_token"];
Token *t = [[Token alloc]init];
[t setAccessToken:token];
NSLog(t);
And this is the error i get:
Create[29485:770358] -[Token _fastCStringContents:]: unrecognized
selector sent to instance 0x7f8e815d0780
Create[29485:770358] * Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[Token _fastCStringContents:]:
unrecognized selector sent to instance 0x7f8e815d0780'
* First throw call stack: ( 0 CoreFoundation 0x000000010149ff45 exceptionPreprocess + 165 1 libobjc.A.dylib
0x0000000100f19deb objc_exception_throw + 48 2 CoreFoundation
0x00000001014a856d -[NSObject(NSObject) doesNotRecognizeSelector:] +
205 3 CoreFoundation 0x00000001013f5eea
___forwarding_ + 970 4 CoreFoundation 0x00000001013f5a98 _CF_forwarding_prep_0 + 120 5
libsystem_trace.dylib 0x00000001036e8327
os_log_shim_with_CFString + 120 6 CoreFoundation
0x000000010148ef24 _CFLogvEx3 + 132 7 Foundation
0x0000000100b9489e _NSLogv + 117 8 Foundation
0x0000000100ae40f2 NSLog + 152 9 Create
0x00000001004d665b 21-[LoginVC UserLogin:]_block_invoke + 203 10
Create 0x00000001004d7f18
__64-[AFHTTPRequestOperation setCompletionBlockWithSuccess:failure:]_block_invoke49 + 40 11
libdispatch.dylib 0x00000001033fde5d
_dispatch_call_block_and_release + 12 12 libdispatch.dylib 0x000000010341e49b _dispatch_client_callout + 8 13 libdispatch.dylib
0x00000001034062af _dispatch_main_queue_callback_4CF + 1738 14
CoreFoundation 0x00000001014002e9
__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 9 15 CoreFoundation 0x00000001013c18a9 __CFRunLoopRun
+ 2073 16 CoreFoundation 0x00000001013c0e08 CFRunLoopRunSpecific + 488 17 GraphicsServices
0x00000001056dcad2 GSEventRunModal + 161 18 UIKit
0x000000010184c30d UIApplicationMain + 171 19 Create
0x00000001004d6a2f main + 111 20 libdyld.dylib
0x000000010345292d start + 1 21 ???
0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with
uncaught exception of type NSException
Hope somebody can help me out!
NSLog(...) function assumes the first argument is an instance of NSString. If you want to use a different object, either use:
NSLog([t description]) or a format string NSLog(#"%#", t).
__block NSArray *arrayImgAssetURL = [[NSUserDefaults standardUserDefaults] objectForKey:#"imgAssetURL"];
// if img url is not available then find image url and save to user default and
if (!arrayImgAssetURL) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
arrayImgAssetURL = [[GALAssetsLibrary sharedReference] readImagesFromGallery];
// write asset image url to user default
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:arrayImgAssetURL
forKey:#"imgAssetURL"];
[userDefaults synchronize];
});
}
Above method is crashed at [userDefaults setObject:arrayImgAssetURL forKey:#"imgAssetURL"];
Method [[GALAssetsLibrary sharedReference] readImagesFromGallery]; return the __block NSArray object, and it is assigned to arrayImgAssetURL which has values. Only when I'm trying to insert into userDefault it is crashed. NSUserDefaults only allow to insert (array, data, string, number, date, dictionary). Then why it is going crash? and what is the solution of this?
Crash log
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[NSUserDefaults setObject:forKey:]:
attempt to insert non-property list object (
"assets-library://asset/asset.JPG?id=E3DCD905-082D-4D0C-886E-55CDFC669D41&ext=JPG",
"assets-library://asset/asset.JPG?id=F471F275-AD0A-489F-9330-CB8A51571087&ext=JPG",
"assets-library://asset/asset.JPG?id=7F313D5B-CA0E-493C-9A1E-AC15BABFC741&ext=JPG",
"assets-library://asset/asset.JPG?id=2270D5A3-0741-4278-9021-79FA89AAB6CB&ext=JPG",
"assets-library://asset/asset.JPG?id=239747B8-0586-490E-BCF1-6BB5675D47EE&ext=JPG",
"assets-library://asset/asset.JPG?id=882487BA-1A54-4B97-8B56-DB5409AB6262&ext=JPG",
"assets-library://asset/asset.JPG?id=88CDC266-CE00-44AB-A24B-9630B27E2AED&ext=JPG",
"assets-library://asset/asset.JPG?id=3B6B3C09-9839-48C2-91EA-B26691445892&ext=JPG"
) for key imgAssetURL'
*** First throw call stack:
(
0 CoreFoundation 0x017f21e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x015718e5 objc_exception_throw + 44
2 CoreFoundation 0x017f1fbb +[NSException raise:format:] + 139
3 Foundation 0x011a4a40 -[NSUserDefaults(NSUserDefaults) setObject:forKey:] + 150
4 FaceDetection 0x0000296d __59-[MCAppDelegate application:didFinishLaunchingWithOptions:]_block_invoke + 237
5 libdispatch.dylib 0x01e377b8 _dispatch_call_block_and_release + 15
6 libdispatch.dylib 0x01e4c4d0 _dispatch_client_callout + 14
7 libdispatch.dylib 0x01e3aeb7 _dispatch_root_queue_drain + 291
8 libdispatch.dylib 0x01e3b127 _dispatch_worker_thread2 + 39
9 libsystem_pthread.dylib 0x021772e3 _pthread_wqthread + 801
10 libsystem_pthread.dylib 0x02174eea start_wqthread + 30
)
libc++abi.dylib: terminating with uncaught exception of type NSException
For the below code snippet:
error occurs at setObject: forKey:
response <--is an NSDictionary
if(response){
NSMutableArray *lifeArray = [[NSMutableArray alloc] init];
NSMutableDictionary *responseDict = [[NSMutableDictionary alloc] init];
responseDict = (NSMutableDictionary *)[response mutableCopy];
[responseDict setObject:#"life" forKey:#"label"]; <-- Error here
}
Note that variable responseDict is NSMutableDictionary since copied via mutableCopy.
Error message:
2014-11-12 12:16:08.534 Lifetape[84381:508759] -[__NSCFArray setObject:forKey:]: unrecognized selector sent to instance 0x7a296700
2014-11-12 12:16:08.536 Lifetape[84381:508759] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray setObject:forKey:]: unrecognized selector sent to instance 0x7a296700'
*** First throw call stack:
(
0 CoreFoundation 0x028fbdf6 __exceptionPreprocess + 182
1 libobjc.A.dylib 0x02557a97 objc_exception_throw + 44
2 CoreFoundation 0x02903a75 -[NSObject(NSObject) doesNotRecognizeSelector:] + 277
3 CoreFoundation 0x0284c9c7 ___forwarding___ + 1047
4 CoreFoundation 0x0284c58e _CF_forwarding_prep_0 + 14
5 Lifetape 0x000dfb83 __50-[LTTimeLineTableViewController getTimeIntervals:]_block_invoke + 307
6 Lifetape 0x0014cedb -[MethodInvoker maybeInvokeCallback] + 395
7 Lifetape 0x0014d19f -[MethodInvoker receiveResultWithError:andResult:] + 399
8 Lifetape 0x00143e38 -[MeteorClient(Connection) livedata_result:] + 1544
9 Lifetape 0x00138674 __54-[MeteorClient(Connection) initConnectionWithOptions:]_block_invoke_3 + 2660
10 Lifetape 0x0014b2b5 -[MeteorClient didReceiveMessage:] + 197
11 Lifetape 0x0014eb7d -[ObjectiveDDP webSocket:didReceiveMessage:] + 269
12 Lifetape 0x0015d986 __30-[SRWebSocket _handleMessage:]_block_invoke + 102
13 libdispatch.dylib 0x031e941a _dispatch_call_block_and_release + 15
14 libdispatch.dylib 0x03209e1f _dispatch_client_callout + 14
15 libdispatch.dylib 0x031f0981 _dispatch_main_queue_callback_4CF + 610
16 CoreFoundation 0x02855f3e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
17 CoreFoundation 0x02814d40 __CFRunLoopRun + 2256
18 CoreFoundation 0x028141ab CFRunLoopRunSpecific + 443
19 CoreFoundation 0x02813fdb CFRunLoopRunInMode + 123
20 GraphicsServices 0x051a524f GSEventRunModal + 192
21 GraphicsServices 0x051a508c GSEventRun + 104
22 UIKit 0x00f41e16 UIApplicationMain + 1526
23 Lifetape 0x000ce36d main + 141
24 libdyld.dylib 0x03235ac9 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Here your response dictionary is a NSDictionary type collection so it does not have any selector like setObject, that's why it is giving you this error use
if(response && [response isKindOfClass:[NSDictionary class]]){
NSMutableArray *lifeArray = [[NSMutableArray alloc] init];
NSMutableDictionary *responseDict = [NSMutableDictionary dictionaryWithDictionary:response];
[responseDict setObject:#"life" forKey:#"label"];
}
and it will work but make sure response is your dictionary type object. as the error you have posted clearly says that your response is an array not a dictionary.
Your response looks like NSArray class so try below code.
if([response isKindOfClass:[NSArray Class]]){
NSLog(#"Array");
}
else if([response isKindOfClass:[NSDictionary Class]]){
NSLog(#"Dictionary");
}
Now manage your code as per log.
I get this exception in my Crashalytics:
0 CoreFoundation
__exceptionPreprocess + 162
1 libobjc.A.dylib
objc_exception_throw + 30
2 CoreFoundation
-[NSException initWithCoder:]
3 CoreFoundation
-[__NSCFArray objectAtIndex:] + 136
4 BusinessPlan ✭ BusinessController.m line 167
-[BusinessController tableView:didSelectRowAtIndexPath:] + 167
5 UIKit
-[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 876
6 UIKit
-[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 156
7 Foundation
__NSFireDelayedPerform + 450
8 CoreFoundation
__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 14
9 CoreFoundation
__CFRunLoopDoTimer + 272
10 CoreFoundation
__CFRunLoopRun + 1232
11 CoreFoundation
CFRunLoopRunSpecific + 356
12 CoreFoundation
CFRunLoopRunInMode + 104
13 GraphicsServices
GSEventRunModal + 74
14 UIKit
UIApplicationMain + 1120
15 BusinessPlan main.m line 16
main + 16
16 BusinessPlan
start
and it is called this:
Exception Type: NSRangeException
Reason: -[__NSCFArray objectAtIndex:]: index (14) beyond bounds (14)
It only happened once so I am not sure how to reproduce it. But it happened in this code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *info = [topics_array objectAtIndex:indexPath.row];
NSString *section_name = [info objectForKey:#"section_name"];
NSString *solution_section_id = [info objectForKey:#"solution_section_id"];
// PUT THESE ITEMS INTO THE SESSION
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:section_name forKey:#"section_name"];
[standardUserDefaults setObject:solution_section_id forKey:#"solution_section_id"];
[standardUserDefaults synchronize];
[self performSegueWithIdentifier:#"BusinessToTopic" sender:self];
}
Would anyone know how to prevent this from happening in the future and why it is happening?
EDIT:
This is the code for tableView numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tableLabels count];
}
Thanks!