Terminating app due to uncaught exception '_HKObjectValidationFailureException' - ios

I am saving the blood glucose values into Health Kit application in iOS.
-(void)viewDidLoad
{
float bloodGlucose=20;
float bloodGlucoseValue= (int) bloodGlucose;
NSLog(#"Blood Glucose value is :%f",bloodGlucoseValue);
HKQuantityType *bloodGlucoseType=[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBloodGlucose];
NSSet *requesObjects=[[NSSet alloc]initWithObjects:bloodGlucoseType, nil];
HKHealthStore * hStore = [HKHealthStore new];
[hStore requestAuthorizationToShareTypes: requesObjects readTypes:requesObjects completion:^(BOOL success, NSError *error) {
//user response processing goes here, i.e.
if(success) {
dispatch_async(dispatch_get_main_queue(), ^{
[[GSHealthKitManager sharedManager]saveBloodGlucosePercentageintoHealthStore:bloodGlucoseValue];
});
}
}];
}
-(void)saveBloodGlucosePercentageintoHealthStore:(float)bloodGlucoseValue
{
HKUnit *inches=[HKUnit gramUnit];
HKQuantity * glucoseQuantity = [HKQuantity quantityWithUnit:inches doubleValue:bloodGlucoseValue];
HKQuantityType *glucoseType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBloodGlucose];
NSDate *now = [NSDate date];
HKQuantitySample *bloodGlucosesample = [HKQuantitySample quantitySampleWithType:glucoseType quantity:glucoseQuantity startDate:now endDate:now];
[self.healthStore saveObject:bloodGlucosesample withCompletion:^(BOOL success, NSError *error){
if (!success)
{
NSLog(#"Error");
}
}];
}
If I run the application, I got following exception in this line of code:
HKQuantitySample *bloodGlucosesample = [HKQuantitySample quantitySampleWithType:glucoseType quantity:glucoseQuantity startDate:now endDate:now];
Trace:
Exception is: Terminating app due to uncaught exception '_HKObjectValidationFailureException', reason: 'HKQuantitySample 20 g 2016-04-07 15:39:44 +0530 2016-04-07 15:39:44 +0530 requires unit of type Mass/Volume. Incompatible unit: g'
*** First throw call stack:
(
0 CoreFoundation 0x00b73a14 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x00634e02 objc_exception_throw + 50
2 CoreFoundation 0x00b7393d +[NSException raise:format:] + 141
3 HealthKit 0x0010da70 -[HKObject _validateForCreation] + 149
4 HealthKit 0x0010d89e +[HKObject _newDataObjectWithMetadata:device:config:] + 273
5 HealthKit 0x0014e661 +[HKSample _newSampleWithType:startDate:endDate:device:metadata:config:] + 200
6 HealthKit 0x0013244f +[HKQuantitySample quantitySampleWithType:quantity:startDate:endDate:device:metadata:] + 324
7 HealthKit 0x0013265a +[HKQuantitySample quantitySampleWithType:quantity:startDate:endDate:] + 116
8 HealthKitProto 0x0005cda2 -[GSHealthKitManager saveBloodGlucosePercentageintoHealthStore:] + 274
9 HealthKitProto 0x0005f4c7 __34-[FirstViewController viewDidLoad]_block_invoke_9 + 103
10 libdispatch.dylib 0x0367a377 _dispatch_call_block_and_release + 15
11 libdispatch.dylib 0x0369d9cd _dispatch_client_callout + 14
12 libdispatch.dylib 0x03682f90 _dispatch_main_queue_callback_4CF + 910
13 CoreFoundation 0x00ac4fde __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
14 CoreFoundation 0x00a82cd4 __CFRunLoopRun + 2356
15 CoreFoundation 0x00a820e6 CFRunLoopRunSpecific + 470
16 CoreFoundation 0x00a81efb CFRunLoopRunInMode + 123
17 GraphicsServices 0x04523664 GSEventRunModal + 192
18 GraphicsServices 0x045234a1 GSEventRun + 104
19 UIKit 0x00f02bfa UIApplicationMain + 160
20 HealthKitProto 0x000603ba main + 138
21 libdyld.dylib 0x036c7a21 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

It seems that grams is not an unit supported by healthkit.
Check the allowed units in the SDK documentation and here
Edit: You specify a bad unit for this value
HKUnit *inches=[HKUnit gramUnit]; // this is not the right unit (nor inches)
HKQuantity * glucoseQuantity = [HKQuantity quantityWithUnit:inches doubleValue:bloodGlucoseValue];
You should create a mass unit and volume unit then divide the first by the second one (in swift):
let milligramPerDeciLiter = HKUnit.gramUnitWithMetricPrefix(.Milli).unitDividedByUnit(HKUnit.literUnitWithMetricPrefix(.Deci))
In Objc :
HKUnit* milligramPerDeciLiter = [[HKUnit gramUnitWithMetricPrefix:HKMetricPrefixMilli] unitDividedByUnit:[HKUnit literUnitWithMetricPrefix:HKMetricPrefixDeci]];

Related

UITraitCollection getter, which is not supported on iOS13

I'm trying to update my project for iOS13. I'm using UIScrollSlidingPages library in my application project.
I put this library in my UIViewController like below. I put my custom view in data source.
- (TTSlidingPage *)pageForSlidingPagesViewController:(TTScrollSlidingPagesController_Custom*)source atIndex:(int)index{
PhotoGalleryItemView *item = [[PhotoGalleryItemView alloc] initPhotoGalleryItem:[restaurantData.Galeri objectAtIndex:index] ParentViewController:self];
item.view.frame = _ViewPhotoContainer.frame;
TTSlidingPage *slidingPage = [[TTSlidingPage alloc] initWithContentViewController:item];
return slidingPage;
}
But when i run the app it crash despite i reload data with DispatchQueue Main Async like these solutions.
2019-11-08 09:42:22.760428+0300 GastroClub[5790:35896] WARNING: GoogleAnalytics 3.17 void GAIUncaughtExceptionHandler(NSException *) (GAIUncaughtExceptionHandler.m:48): Uncaught exception: <PhotoGalleryItemView: 0x7f9eb1782db0> returned nil from -traitCollection, which is not allowed.
2019-11-08 09:42:22.925971+0300 GastroClub[5790:35896] invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.
2019-11-08 09:42:22.988883+0300 GastroClub[5790:35896] *** Assertion failure in UITraitCollection * _Nonnull _UIGetCurrentFallbackTraitCollection(void)(), /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3900.12.15/_UIFallbackEnvironment.m:91
2019-11-08 09:42:22.990119+0300 GastroClub[5790:35896] *** WebKit discarded an uncaught exception in the webView:didFinishLoadForFrame: delegate: <NSInternalInconsistencyException> <PhotoGalleryItemView: 0x7f9eb1782db0> returned nil from -traitCollection, which is not allowed.
2019-11-08 09:42:27.776557+0300 GastroClub[5790:35896] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '<PhotoGalleryItemView: 0x7f9eb1782db0> returned nil from -traitCollection, which is not allowed.'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff23c4f02e __exceptionPreprocess + 350
1 libobjc.A.dylib 0x00007fff50b97b20 objc_exception_throw + 48
2 CoreFoundation 0x00007fff23c4eda8 +[NSException raise:format:arguments:] + 88
3 Foundation 0x00007fff256c9c2a -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 166
4 UIKitCore 0x00007fff474abd67 _UIGetCurrentFallbackTraitCollection + 962
5 UIKitCore 0x00007fff47d00909 UIViewCommonInitWithFrame + 644
6 UIKitCore 0x00007fff47d00647 -[UIView initWithFrame:] + 98
7 UIKitCore 0x00007fff47cde48f -[UIImageView initWithFrame:] + 62
8 UIKitCore 0x00007fff47cffe99 -[UIView init] + 44
9 GastroClub 0x000000010816d313 -[UIImageView(Preloader) addPreloder] + 131
10 GastroClub 0x000000010816dcf6 -[UIImageView(Preloader) setImageWithURL_ShowPreloader:placeholderImage:options:progress:completed:] + 182
11 GastroClub 0x000000010816db69 -[UIImageView(Preloader) setImageWithURL_ShowPreloader:] + 105
12 GastroClub 0x00000001080c29f8 -[PhotoGalleryItemView viewDidLoad] + 200
13 UIKitCore 0x00007fff471cdb45 -[UIViewController _sendViewDidLoadWithAppearanceProxyObjectTaggingEnabled] + 83
14 UIKitCore 0x00007fff471d2a9e -[UIViewController loadViewIfRequired] + 1084
15 UIKitCore 0x00007fff471d2ebb -[UIViewController view] + 27
16 UIScrollSlidingPages 0x000000010a06f2fd -[TTSlidingPage setContentViewController:] + 93
17 UIScrollSlidingPages 0x000000010a06f18b -[TTSlidingPage initWithContentViewController:] + 139
18 GastroClub 0x000000010806b32d -[RestaurantDetailViewController pageForSlidingPagesViewController:atIndex:] + 429
19 UIScrollSlidingPages 0x000000010a06b6cf -[TTScrollSlidingPagesController reloadPages] + 3455
20 GastroClub 0x0000000108060d42 __48-[RestaurantDetailViewController addPhotoSlider]_block_invoke + 50
21 libdispatch.dylib 0x000000010abc6dd4 _dispatch_call_block_and_release + 12
22 libdispatch.dylib 0x000000010abc7d48 _dispatch_client_callout + 8
23 libdispatch.dylib 0x000000010abd5de6 _dispatch_main_queue_callback_4CF + 1500
24 CoreFoundation 0x00007fff23bb1df9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
25 CoreFoundation 0x00007fff23baca59 __CFRunLoopRun + 2329
26 CoreFoundation 0x00007fff23babe16 CFRunLoopRunSpecific + 438
27 GraphicsServices 0x00007fff38438bb0 GSEventRunModal + 65
28 UIKitCore 0x00007fff4784fb68 UIApplicationMain + 1621
29 GastroClub 0x000000010801b900 main + 112
30 libdyld.dylib 0x00007fff51a1dc25 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Then i tried to fix that with this solution. I put this method in my custom view like below:
#interface PhotoGalleryItemView (){
GCGaleri *galleryItem;
}
#property (weak, nonatomic) IBOutlet UIImageView *IMGViewGallery;
#end
#implementation PhotoGalleryItemView
- (id)initPhotoGalleryItem:(GCGaleri*)GalleryItem ParentViewController :(RestaurantDetailViewController*)ParentViewController {
if (self) {
galleryItem = GalleryItem;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[_IMGViewGallery setImageWithURL_ShowPreloader:[NSURL URLWithString:galleryItem.Foto]];
_IMGViewGallery.clipsToBounds = YES;
_IMGViewGallery.contentMode = UIViewContentModeScaleAspectFill;
}
// I put here
- (UITraitCollection *)traitCollection
{
if (#available(iOS 13.0, *)) {
[UITraitCollection setCurrentTraitCollection:[[UITraitCollection alloc]init]];
} else {
// Fallback on earlier versions
};
return [[UITraitCollection alloc]init];
}
#end
After that, i run my app it crash with these errors:
2019-11-08 10:03:40.570894+0300 GastroClub[5914:42170] [TraitCollection] Class PhotoGalleryItemView overrides the -traitCollection getter, which is not supported. If you're trying to override traits, you must use the appropriate API.
2019-11-08 10:03:40.571987+0300 GastroClub[5914:42170] [Assert] Current fallback trait collection contains one or more unspecified traits: {(
"_UITraitNameDisplayGamut",
"_UITraitNameDebugHighlight",
"_UITraitNameDisplayScale",
"_UITraitNameDisplayCornerRadius",
"_UITraitNamePresentationSemanticContext",
"_UITraitNameUserInterfaceLevel",
"_UITraitNameVibrancy",
"_UITraitNameLegibilityWeight",
"_UITraitNamePreferredContentSizeCategory",
"_UITraitNameAccessibilityContrast",
"_UITraitNameTouchLevel",
"_UITraitNameSemanticContext"
)}; traitCollection: <UITraitCollection: 0x600001984600; >; currentFallbackEnvironment: <PhotoGalleryItemView: 0x7fdeb1e9cac0>
How can i fix that issue? I can not update my library because it is no longer in active development.
I found the solution. When I slidingPage initiate then I show a preloader. My crash has occurred when I show the preloader. When I put my preloader in DispatchAsyncAfter like below I could fix my error:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self addPreloder];
__weak typeof(self) weakSelf = self;
[self sd_setImageWithURL:url
placeholderImage:placeholder
options:options
progress:progressBlock
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageUrl) {
if (completedBlock) {
completedBlock(image, error, cacheType, imageUrl);
}
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (weakSelf.preloding) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
[weakSelf.preloding stopAnimating];
[weakSelf.preloding removeFromSuperview];
[weakSelf removeActivityIndicator];
});
}
});
}
];
});
In swift 5 it work for me
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(0.5 * Double(NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
// your code here
})

NSMutableDictionary setobject: forkey: crashes with unrecognised selector message

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.

Firebase simple login error "__NSPlaceholderDictionary initWithObjects:forKeys:count:"

I'm trying to get simple login with email and password on iOS. I got the following error when logging in.
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '* -[__NSPlaceholderDictionary
initWithObjects:forKeys:count:]: attempt to insert nil object from
objects[0]'
* First throw call stack: ( 0 CoreFoundation 0x02eee1e4 exceptionPreprocess + 180 1 libobjc.A.dylib
0x02c6d8e5 objc_exception_throw + 44 2 CoreFoundation
0x02eb4376 -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]
+ 390 3 CoreFoundation 0x02ee1c29 +[NSDictionary dictionaryWithObjects:forKeys:count:] + 73 4 app 0x000ed30c ParseUserData + 428 5 app
0x0009e6e1 __37-[MenuViewController checkAuthStatus]_block_invoke +
161 6 app 0x0011f89f
__82-[FirebaseSimpleLogin attemptAuthWithToken:provider:userData:account:andCallback:]_block_invoke
+ 461 7 app 0x00199df7 __43-[FRepo callOnComplete:withStatus:andData:]_block_invoke + 33 8
libdispatch.dylib 0x06e457b8
_dispatch_call_block_and_release + 15 9 libdispatch.dylib 0x06e5a4d0 _dispatch_client_callout + 14 10 libdispatch.dylib
0x06e48726 _dispatch_main_queue_callback_4CF + 340 11 CoreFoundation
0x02f5343e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 14 12
CoreFoundation 0x02e945cb __CFRunLoopRun + 1963
13 CoreFoundation 0x02e939d3
CFRunLoopRunSpecific + 467 14 CoreFoundation
0x02e937eb CFRunLoopRunInMode + 123 15 GraphicsServices
0x03d535ee GSEventRunModal + 192 16 GraphicsServices
0x03d5342b GSEventRun + 104 17 UIKit
0x0192df9b UIApplicationMain + 1225 18 app
0x0010623d main + 141 19 libdyld.dylib
0x0708f701 start + 1 20 ???
0x00000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught
exception of type NSException
My code:
Firebase *ref = [[Firebase alloc] initWithUrl:FIREBASE];
FirebaseSimpleLogin *authClient = [[FirebaseSimpleLogin alloc] initWithRef:ref];
[authClient loginWithEmail:#"useremail" andPassword:#"userPassword"
withCompletionBlock:^(NSError* error, FAUser* user) {
if (error != nil) {
NSLog(#"Success!");
// There was an error logging in to this account
} else {
NSString *message = [error.userInfo valueForKey:#"NSLocalizedDescription"];
if (message == nil) message = #"Please try again";
[self performSelectorOnMainThread:#selector(showError:) withObject:message waitUntilDone:NO];
}
}];
Getting this error, my app don't get data form database anymore with crash.. Anybody have any idea?
Look at the stack trace. The error is in your method ParseUserData, which you didn't show. In that method you are trying to create a dictionary, but the first of the objects that you pass in is nil.
In Xcode, set a breakpoint that triggers when exceptions are thrown, so the next time you can check in your running program what happens.

Issue Paging with UITableView

Im trying to create an infinite scroll type thing with Instagram using UITableView and AFNetworking however I get this error when I get to the bottom of the View:
CRASH :
-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object
2014-01-05 20:51:41.627 Floadt[1579:70b] STACK TRACE :
(
0 CoreFoundation 0x02b775e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x027a38b6 objc_exception_throw + 44
2 CoreFoundation 0x02b773bb +[NSException raise:format:] + 139
3 CoreFoundation 0x02bfe365 -[__NSCFArray insertObject:atIndex:] + 101
4 CoreFoundation 0x02b3b2d0 -[NSMutableArray insertObjects:count:atIndex:] + 208
5 CoreFoundation 0x02b3af69 -[NSMutableArray insertObjectsFromArray:range:atIndex:] + 425
6 CoreFoundation 0x02b3ad15 -[NSMutableArray addObjectsFromArray:] + 661
7 Floadt 0x0003f5ec __42-[StreamViewController nextInstagramPage:]_block_invoke + 284
8 Floadt 0x0001edfb __64-[AFJSONRequestOperation setCompletionBlockWithSuccess:failure:]_block_invoke91 + 43
9 libdispatch.dylib 0x035247f8 _dispatch_call_block_and_release + 15
10 libdispatch.dylib 0x035394b0 _dispatch_client_callout + 14
11 libdispatch.dylib 0x0352775e _dispatch_main_queue_callback_4CF + 340
12 CoreFoundation 0x02bdca5e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
13 CoreFoundation 0x02b1d6bb __CFRunLoopRun + 1963
14 CoreFoundation 0x02b1cac3 CFRunLoopRunSpecific + 467
15 CoreFoundation 0x02b1c8db CFRunLoopRunInMode + 123
16 GraphicsServices 0x0453c9e2 GSEventRunModal + 192
17 GraphicsServices 0x0453c809 GSEventRun + 104
18 UIKit 0x01936d3b UIApplicationMain + 1225
19 Floadt 0x0006646d main + 141
20 libdyld.dylib 0x037cb70d start + 1
21 ??? 0x00000001 0x0 + 1
)
Here is how I am making my code, what confuses me is the fact that all my Arrays are Mutable but it states that the mutating method was sent to an immutable object:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView.contentOffset.y == roundf(scrollView.contentSize.height-scrollView.frame.size.height)) {
NSDictionary *page = instagramResponse[#"pagination"];
NSString *nextPage = page[#"next_url"];
[[InstagramClient sharedClient] getPath:[NSString stringWithFormat:#"%#",nextPage] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
instagramResponse = [responseObject mutableCopy];
[instagramResponse addEntriesFromDictionary:responseObject];
[instaPics addObjectsFromArray:responseObject[#"data"]];
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
}
}
before addEntriesFromDictionary the copy of Dictionarylike this
NSDictionary *copyOfDic = [[NSDictionary alloc] initWithDictionary: originalDic copyItems: YES];
if (copyOfDic ) {
[destination addEntriesFromDictionary: copyOfDic ];
[copyOfDic release];
}
or
[instaPics addObjectsFromArray:[responseObject[#"data"]mutable copy]];
or
Your #property yourarray is either initialized with an NSArray or declared copy.
because both would be lead to this error/exception message since the backing ivar would point to an (immutable) NSArray.
If you have declared your property to be of NSMutableArray type, use strong as the storage modifier instead of copy.

How could to-one relationship degenerate into NSManagedObjectID in willTurnIntoFault?

Here is the code:
- (void)willTurnIntoFault {
NSManagedObject *relatedObject = self.relatedObject;
if (relatedObject != nil && !relatedObject.isFault && !relatedObject.hasChanges) {
[relatedObject.managedObjectContext refreshObject:relatedObject mergeChanges:NO];
}
[super willTurnIntoFault];
}
Here is the crash:
Application Specific Information:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSObjectID_64_1 hasChanges]: unrecognized selector sent to instance 0x158601a0'
Last Exception Backtrace:
0 CoreFoundation 0x307bfe8b __exceptionPreprocess + 131
1 libobjc.A.dylib 0x3aab96c7 _objc_exception_throw + 39
2 CoreFoundation 0x307c37b7 -[NSObject(NSObject) doesNotRecognizeSelector:] + 203
3 CoreFoundation 0x307c20b7 ___forwarding___ + 707
4 CoreFoundation 0x30710e98 __CF_forwarding_prep_0 + 24
5 Moke 0x0017cd51 -[Status willTurnIntoFault] (Status.m:420)
6 CoreData 0x305356eb -[NSFaultHandler turnObject:intoFaultWithContext:] + 67
7 CoreData 0x305333bb -[NSManagedObject dealloc] + 75
8 CoreData 0x30532b85 -[_PFManagedObjectReferenceQueue _processReferenceQueue:] + 1557
9 CoreData 0x305393c7 -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 3795
10 CoreData 0x30532505 _performRunLoopAction + 317
11 CoreFoundation 0x3078af71 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 21
12 CoreFoundation 0x307888ff __CFRunLoopDoObservers + 287
13 CoreFoundation 0x30788c4b __CFRunLoopRun + 739
14 CoreFoundation 0x306f3541 _CFRunLoopRunSpecific + 525
15 CoreFoundation 0x306f3323 _CFRunLoopRunInMode + 107
16 GraphicsServices 0x3542a2eb _GSEventRunModal + 139
17 UIKit 0x32faa1e5 _UIApplicationMain + 1137
18 Moke 0x000f47e7 main (main.m:16)
19 libdyld.dylib 0x3afb2ab7 start + 3
Here is the self object:
<Status: 0x16a705c0> (entity: Status; id: 0x16a31700 <x-coredata://66EAF889-7CD5-48C2-999E-5E15B84BF8FA/Status/p2235> ; data: {
ID = 3622738251833351;
relatedObject = "0x16a40340 <x-coredata://66EAF889-7CD5-48C2-999E-5E15B84BF8FA/Status/p2242>";
text = "...";
user = "0x16824200 <x-coredata://66EAF889-7CD5-48C2-999E-5E15B84BF8FA/User/p948>";
})
So it seems in this conditional !relatedObject.hasChanges relatedObject becomes _NSObjectID_64_1(which is a subclass of NSManagedObjectID). But how could it be?
PS: If you are curious why it doesn't crash at !relatedObject.isFault, it is because _NSObjectID_64_1 does implement ifFault by my test.
It seems like you are transferring your managed objects between threads. Try to enhance your code this way:
//NSManagedObject *relatedObject = self.relatedObject;
NSManagedObject *relatedObject = [self.managedObjectContext existingObjectWithID:self.relatedObject.objectID error:nil];
Can you call a message as a property ? As far as I know, hasChanges and isFault are messages.
I think it should be :-
if (relatedObject != nil && !([relatedObject isFault]) && !([relatedObject.hasChanges]))

Resources