In order to detect the behavior of refresh UI on background thread,I used the third-part library ODUIThreadGuard.
This lib is based on hook UIView's setNeedsLayout、setNeedsDisplay、setNeedsDisplayInRect selector.
When I tested it, I found that UILabel's setFrame: on background thread can be detected but UIView's can't.Who can tell me why?
code:
// ViewController.m
[self.view addSubview:self.testLabel];
[self.view addSubview:self.testView];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
self.testLabel.frame = CGRectMake(20, 20, 100, 100);
});
The above code will be detected but the following will not .
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
self.testView.frame = CGRectMake(20, 20, 100, 100);
});
hook code :
#implementation UIView (ThreadSafeGuard)
+ (void)load {
[DBHookUtil swizzlingInClass:[self class] originalSelector:#selector(setNeedsLayout) swizzledSelector:#selector(db_setNeedsLayout)];
[DBHookUtil swizzlingInClass:[self class] originalSelector:#selector(setNeedsDisplay) swizzledSelector:#selector(db_setNeedsDisplay)];
[DBHookUtil swizzlingInClass:[self class] originalSelector:#selector(setNeedsDisplayInRect:) swizzledSelector:#selector(db_setNeedsDisplayInRect:)];
}
- (void)db_setNeedsLayout {
NSAssert([NSThread isMainThread], #"refresh UI on background thread");
[self db_setNeedsLayout];
}
- (void)db_setNeedsDisplay {
NSAssert([NSThread isMainThread], #"refresh UI on background thread");
[self db_setNeedsDisplay];
}
- (void)db_setNeedsDisplayInRect:(CGRect)rect {
NSAssert([NSThread isMainThread], #"refresh UI on background thread");
[self db_setNeedsDisplayInRect:rect];
}
#end
crash log:
2017-05-15 18:17:40.876 ThreadSafeGuardDemo[50800:19659410] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'refresh UI on background thread'
*** First throw call stack:
(
0 CoreFoundation 0x0000000105181b0b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x0000000104be6141 objc_exception_throw + 48
2 CoreFoundation 0x0000000105185cf2 +[NSException raise:format:arguments:] + 98
3 Foundation 0x00000001047803b6 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
4 ThreadSafeGuardDemo 0x0000000104615068 -[UIView(ThreadSafeGuard) db_setNeedsDisplay] + 264
5 UIKit 0x00000001058311f6 -[UILabel setNeedsDisplay] + 55
6 UIKit 0x00000001058279e6 -[UILabel _invalidateAsNeededForNewSize:oldSize:withLinkCheck:] + 336
7 UIKit 0x0000000105827c9f -[UILabel setFrame:] + 76
8 ThreadSafeGuardDemo 0x0000000104614a76 __29-[ViewController viewDidLoad]_block_invoke + 278
9 libdispatch.dylib 0x0000000107f744a6 _dispatch_call_block_and_release + 12
10 libdispatch.dylib 0x0000000107f9d05c _dispatch_client_callout + 8
11 libdispatch.dylib 0x0000000107f7f198 _dispatch_root_queue_drain + 1358
12 libdispatch.dylib 0x0000000107f7ebef _dispatch_worker_thread3 + 123
13 libsystem_pthread.dylib 0x00000001083c3746 _pthread_wqthread + 1299
14 libsystem_pthread.dylib 0x00000001083c3221 start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Related
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
})
Here is my sampleCode :
-(IBAction)add:(id)sender {
//ShoppingManager sharedManager is a singleton
[[ShoppingManager sharedManager].onlineClassArray addObject:#(1)];
}
and code in ShoppingManager.m:
//singleton
+ (ShoppingManager *)sharedManager{
static id instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc]init];
});
return instance;
}
- (OnlineClassItemizeArray *)onlineClassArray{
if (!_onlineClassArray) {
_onlineClassArray = [OnlineClassItemizeArray array];
}
return _onlineClassArray;
}
and the ShoppingMananger.h:
#interface ShoppingManager : NSObject
#property(nonatomic,strong) OnlineClassItemizeArray * onlineClassArray;
+ (ShoppingManager*)sharedManager;
#end
I don't know what is wrong with these codes.when i added some object into the mutableArray,it stopped at this line:(a all Exception BreakPoint)
_onlineClassArray = [OnlineClassItemizeArray array];
than crushed at here:
DISPATCH_INLINE DISPATCH_ALWAYS_INLINE DISPATCH_NONNULL_ALL DISPATCH_NOTHROW
DISPATCH_SWIFT3_UNAVAILABLE("Use lazily initialized globals instead")
void
_dispatch_once(dispatch_once_t *predicate,
DISPATCH_NOESCAPE dispatch_block_t block)
{
if (DISPATCH_EXPECT(*predicate, ~0l) != ~0l) {
dispatch_once(predicate, block);//<---crushed here
} else {
dispatch_compiler_barrier();
}
DISPATCH_COMPILER_CAN_ASSUME(*predicate == ~0l);
}
and here is the whole error msg:
2017-03-14 01:01:36.586 tesr1111[7075:1333259] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableArray initWithCapacity:]: method only defined for abstract class. Define -[OnlineClassItemizeArray initWithCapacity:]!'
*** First throw call stack:
(
0 CoreFoundation 0x00000001100c4d4b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010fb2621e objc_exception_throw + 48
2 CoreFoundation 0x00000001101357df __CFRequireConcreteImplementation + 255
3 CoreFoundation 0x00000001101241a7 -[NSMutableArray initWithCapacity:] + 39
4 tesr1111 0x000000010f54e6d0 -[ShoppingManager init] + 160
5 tesr1111 0x000000010f54e5f1 __32+[ShoppingManager sharedManager]_block_invoke + 65
6 libdispatch.dylib 0x0000000112eda0cd _dispatch_client_callout + 8
7 libdispatch.dylib 0x0000000112ebf1f8 dispatch_once_f + 501
8 tesr1111 0x000000010f54e588 +[ShoppingManager sharedManager] + 136
9 tesr1111 0x000000010f54de9d -[ViewController add:] + 61
10 UIKit 0x00000001104ea8bc -[UIApplication sendAction:to:from:forEvent:] + 83
11 UIKit 0x0000000110670c38 -[UIControl sendAction:to:forEvent:] + 67
12 UIKit 0x0000000110670f51 -[UIControl _sendActionsForEvents:withEvent:] + 444
13 UIKit 0x000000011066fe4d -[UIControl touchesEnded:withEvent:] + 668
14 UIKit 0x0000000110558545 -[UIWindow _sendTouchesForEvent:] + 2747
15 UIKit 0x0000000110559c33 -[UIWindow sendEvent:] + 4011
16 UIKit 0x00000001105069ab -[UIApplication sendEvent:] + 371
17 UIKit 0x0000000120cca481 -[UIApplicationAccessibility sendEvent:] + 93
18 UIKit 0x0000000110cf372d __dispatchPreprocessedEventFromEventQueue + 3248
19 UIKit 0x0000000110cec463 __handleEventQueue + 4879
20 CoreFoundation 0x0000000110069761 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
21 CoreFoundation 0x000000011004e98c __CFRunLoopDoSources0 + 556
22 CoreFoundation 0x000000011004de76 __CFRunLoopRun + 918
23 CoreFoundation 0x000000011004d884 CFRunLoopRunSpecific + 420
24 GraphicsServices 0x0000000113eb0a6f GSEventRunModal + 161
25 UIKit 0x00000001104e8c68 UIApplicationMain + 159
26 tesr1111 0x000000010f54e4df main + 111
27 libdyld.dylib 0x0000000112f2668d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
If anyone can give me any idea or helping link. Thanks in advance.
You are subclassing NSMutableArray incorrectly. It is a class cluster and there is a minimum set of methods that need to be implemented.
In this case, you are calling initWithCapacity: but haven't overridden that method. Or, more likely, you are calling a generic method (init) that calls through to that method.
Exactly as the exception says:
2017-03-14 01:01:36.586 tesr1111[7075:1333259] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' -[NSMutableArray initWithCapacity:]: method only defined for abstract class. Define -[OnlineClassItemizeArray initWithCapacity:]!'
However, subclassing the collection classes is a code smell. It is pretty much never done. There are rare cases where it makes sense; what is yours?
I perform a transition between views with an animation. It sometimes works, and it also sometimes causes a crash and I don't understand why. I have my code within a #try-#catch block but no exception is retrieved in #catch. I simply get an app crash with a SIGABRT signal and the following log:
2015-09-23 10:03:43.420 My App[1510:528283] The view hierarchy is not prepared for the constraint:
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.
2015-09-23 10:03:43.421 My App[1510:528283] *** Assertion failure in -[UIView _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3505.16/NSLayoutConstraint_UIKitAdditions.m:590
I don't understand why it sometimes works and other times it crashes, and I don't understand how can I debug this, please I need help.
Thanks in advance
EDIT:
This is the method that seems to cause the app crashes:
- (void)switchToMainView
{
[UIView transitionWithView:self.view
duration:1.0
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
#try {
if ([self.secView superview]) {
[self setMainView];
[self.secView removeFromSuperview];
[self.view addSubview:self.mainView];
[self.view sendSubviewToBack:self.secView];
}
}
#catch (NSException *exception) {
NSLog(#"exception: %#", exception.description);
}
}
completion:^(BOOL finished){
if (finished) {
#try {
[self.view setNeedsUpdateConstraints];
[self setMessage];
}
#catch (NSException *exception) {
NSLog(#"exception: %#", exception.description);
}
}
}];
}
And the setMessage method that is called in the completion block:
- (void)setMessage
{
UIView *messageView = nil;
#try {
messageView = [[[NSBundle mainBundle] loadNibNamed:#"MessageView" owner:nil options:nil] firstObject];
messageView.frame = CGRectMake(0, 0, self.messagesContainerView.frame.size.width, self.messagesContainerView.frame.size.height);
[self.messagesContainerView.subviews makeObjectsPerformSelector: #selector(removeFromSuperview)];
[self.messagesContainerView addSubview:messageView];
}
#catch (NSException *exception) {
NSLog(#"exception: %#", exception.description);
}
}
where self.messagesContainerView is a subview of self.mainView in the first method.
Thanks again
EDIT 2:
This is the last crash information I managed to get:
Date/Time: 2015-09-24 10:01:13 +0000 OS Version: iPhone OS
9.0 (13A344) Report Version: 104
Exception Type: SIGABRT Exception Codes: #0 at 0x34de0d24 Crashed
Thread: 0
Application Specific Information:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Impossible to set up
layout with view hierarchy unprepared for constraint.'
Last Exception Backtrace: 0 CoreFoundation
0x22ee786b 0x22df2000 + 1005675 1 libobjc.A.dylib
0x345e6dff 0x345e0000 + 28159 2 CoreFoundation
0x22ee7741 0x22df2000 + 1005377 3 Foundation
0x23c772ab 0x23be0000 + 619179 4 UIKit
0x277ced17 0x26fe7000 + 8289559 5 UIKit
0x270f8b1b 0x26fe7000 + 1121051 6 UIKit
0x270f898d 0x26fe7000 + 1120653 7 UIKit
0x270f88a7 0x26fe7000 + 1120423 8 UIKit
0x277cee6d 0x26fe7000 + 8289901 9 UIKit
0x270f878f 0x26fe7000 + 1120143 10 My App
0x000423c5 0x11000 + 201669 11 UIKit
0x277d479d 0x26fe7000 + 8312733 12 Foundation
0x23c29c81 0x23be0000 + 302209 13 UIKit
0x270fbaa9 0x26fe7000 + 1133225 14 UIKit
0x277d49d9 0x26fe7000 + 8313305 15 UIKit
0x270fc78b 0x26fe7000 + 1136523 16 Foundation
0x23c29c81 0x23be0000 + 302209 17 UIKit
0x270fbaa9 0x26fe7000 + 1133225 18 UIKit
0x270fc487 0x26fe7000 + 1135751 19 UIKit
0x277d4fa5 0x26fe7000 + 8314789 20 UIKit
0x272edfa9 0x26fe7000 + 3174313 21 UIKit
0x26ff56bb 0x26fe7000 + 59067 22 QuartzCore
0x268c167d 0x268b4000 + 54909 23 QuartzCore
0x268bcd79 0x268b4000 + 36217 24 QuartzCore
0x268bcc09 0x268b4000 + 35849 25 QuartzCore
0x268bc129 0x268b4000 + 33065 26 QuartzCore
0x268bbdeb 0x268b4000 + 32235 27 QuartzCore
0x268b55bf 0x268b4000 + 5567 28 CoreFoundation
0x22eaa0f1 0x22df2000 + 753905 29 CoreFoundation
0x22ea83e7 0x22df2000 + 746471 30 CoreFoundation
0x22ea8825 0x22df2000 + 747557 31 CoreFoundation
0x22dfb1e9 0x22df2000 + 37353 32 CoreFoundation
0x22dfafdd 0x22df2000 + 36829 33 GraphicsServices
0x2c09faf9 0x2c096000 + 39673 34 UIKit
0x2706018d 0x26fe7000 + 496013 35 My App
0x000d7d69 0x11000 + 814441 36 libdyld.dylib
0x34d11873 0x34d0f000 + 10355
Thread 0 Crashed: 0 libsystem_kernel.dylib 0x34de0d24
0x34dcc000 + 85284 1 libsystem_c.dylib 0x34d78f51
0x34d2e000 + 307025 2 My App 0x001abebf
0x11000 + 1683135 3 CoreFoundation 0x22ee7ba9
0x22df2000 + 1006505 4 libobjc.A.dylib
0x345e7087 0x345e0000 + 28807 5 libc++abi.dylib
0x33dcce17 0x33db6000 + 93719 6 libc++abi.dylib
0x33dcc8f7 0x33db6000 + 92407 7 libobjc.A.dylib
0x345e6f47 0x345e0000 + 28487 8 CoreFoundation
0x22dfb26f 0x22df2000 + 37487 9 CoreFoundation
0x22dfafdd 0x22df2000 + 36829 10 GraphicsServices
0x2c09faf9 0x2c096000 + 39673 11 UIKit
0x2706018d 0x26fe7000 + 496013 12 My App
0x000d7d69 0x11000 + 814441 13 libdyld.dylib
0x34d11873 0x34d0f000 + 10355
Without seeing your code It's hard to debug the actual problem. The probably causes are:
You are adding a constraint to a view that is not a superview of the constrained class.
You are adding a constraint to a view that has not been added as a subview yet - and so is not in the view hierarchy.
As to fixing it. I managed to create a project which crashes in this way, and correctly found the mistake by adding a symbolic breakpoint as the error suggests:
So try this and see where your problem is coming from.
When i press my button, i got a error of access.
the error : Thread 1 : EXC_BAD_ACCESS(code=1,address=0xd0a937db)
TTest.h
#interface TTtest : NSObject
{
UIButton *monBouton ;
UIImage *skin;
}
- (void)initTest :(UIView*)vueDonne;
-(void)test:(id)sender;
TTest.m
- (void)initTest :(UIView*)vueDonne
{
skin = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:#"boutonG" ofType:#"png"]];
monBouton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
monBouton.frame = CGRectMake(50, 50, 45, 50);
[monBouton setImage:skin forState:UIControlStateNormal];
[monBouton addTarget:self action:#selector(test:) forControlEvents:UIControlEventTouchDown];
[vueDonne addSubview: monBouton];
}
-(void)test:(id)sender //didn't work because i have the probleme
{
NSLog(#"test clicked");
}
testViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
TTtest *test =[[TTtest alloc] init];
[test initTest:_testView]; //View of my application
}
EDIT:
If i add monBouton = [[UIButton alloc] init];
I get a problem of SIGABRT
2014-10-26 16:47:22.827 testAsk[2134:a0b] -[CALayerArray test:]: unrecognized selector sent to instance 0xa141ea0
2014-10-26 16:47:22.831 testAsk[2134:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CALayerArray test:]: unrecognized selector sent to instance 0xa141ea0'
*** First throw call stack:
(
0 CoreFoundation 0x017395e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x014bc8b6 objc_exception_throw + 44
2 CoreFoundation 0x017d6903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x0172990b ___forwarding___ + 1019
4 CoreFoundation 0x017294ee _CF_forwarding_prep_0 + 14
5 libobjc.A.dylib 0x014ce874 -[NSObject performSelector:withObject:withObject:] + 77
6 UIKit 0x0022c0c2 -[UIApplication sendAction:to:from:forEvent:] + 108
7 UIKit 0x0022c04e -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61
8 UIKit 0x003240c1 -[UIControl sendAction:to:forEvent:] + 66
9 UIKit 0x00324484 -[UIControl _sendActionsForEvents:withEvent:] + 577
10 UIKit 0x003231fd -[UIControl touchesBegan:withEvent:] + 254
11 UIKit 0x0026934b -[UIWindow _sendTouchesForEvent:] + 386
12 UIKit 0x0026a184 -[UIWindow sendEvent:] + 1232
13 UIKit 0x0023de86 -[UIApplication sendEvent:] + 242
14 UIKit 0x0022818f _UIApplicationHandleEventQueue + 11421
15 CoreFoundation 0x016c283f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
16 CoreFoundation 0x016c21cb __CFRunLoopDoSources0 + 235
17 CoreFoundation 0x016df29e __CFRunLoopRun + 910
18 CoreFoundation 0x016deac3 CFRunLoopRunSpecific + 467
19 CoreFoundation 0x016de8db CFRunLoopRunInMode + 123
20 GraphicsServices 0x0368e9e2 GSEventRunModal + 192
21 GraphicsServices 0x0368e809 GSEventRun + 104
22 UIKit 0x0022ad3b UIApplicationMain + 1225
23 testAsk 0x000027bd main + 141
24 libdyld.dylib 0x01d75725 start + 0
25 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
The reason for the crash is that test object is dealloced when it receives the button action.
TTtest *test =[[TTtest alloc] init]; //dealloced after viewDidLoad
so try to make the test a property and use self.test.
self.test =[[TTtest alloc] init];
Doesn't look like you defined the selector "test"
-(void)test: (id) sender
NSLog(#"test clicked");
}
So I have a class, CustomCell : UITableViewCell with a single addObserver:forKeyPath:options:context: method, called in -awakeFromNib, and a single removeObserver:forKeyPath:context: method, called in -dealloc.
CustomCell.m
static void * const MyClassKVOContext = (void*)&MyClassKVOContext; // unique context
-(void)awakeFromNib
{
[super awakeFromNib];
[self registerAsLocationListener];
}
-(void)registerAsLocationListener
{
if ([self.reuseIdentifier isEqualToString:#"locationcell1"])
{
[[RA_LocationSingleton locationSingleton]
addObserver:self
forKeyPath:#"currentLocation"
options:NSKeyValueObservingOptionNew
context:MyClassKVOContext];
NSLog(#"Registered for currentLocation");
NSLog(#"self.description: %#", [self description]);
}
}
-(void)dealloc
{
if ([self.reuseIdentifier isEqualToString:#"locationcell1"])
{
NSLog(#"Attempting to deregister");
NSlog(#"self.description: %#", [self description]);
[self removeObserver:self
forKeyPath:#"currentLocation"
context:MyClassKVOContext];
}
// [super dealloc]; called automatically, using ARC
}
I get the following log, after loading the view with these cells, then backing out again (triggering the dealloc)
// load view
2014-09-01 14:27:33.704 Rally[2931:60b] Registered for currentLocation
2014-09-01 14:27:33.705 Rally[2931:60b] self.description: <CustomCell: 0x9afa570; baseClass = UITableViewCell; frame = (0 0; 320 44); autoresize = RM+BM; layer = <CALayer: 0x9afa710>>
// exit from view
2014-09-01 14:27:40.867 Rally[2931:60b] Attempting to deregister
2014-09-01 14:27:40.868 Rally[2931:60b] self.description: <CustomCell: 0x9afa570; baseClass = UITableViewCell; frame = (0 231; 320 44); autoresize = W; layer = <CALayer: 0x9afa710>>
2014-09-01 14:27:40.870 Rally[2931:60b] *** Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <CustomCell 0x9afa570> for the key path "currentLocation" from <CustomCell 0x9afa570> because it is not registered as an observer.'
*** First throw call stack:
(
0 CoreFoundation 0x026761e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x023f58e5 objc_exception_throw + 44
2 CoreFoundation 0x02675fbb +[NSException raise:format:] + 139
3 Foundation 0x0204346d -[NSObject(NSKeyValueObserverRegistration) _removeObserver:forProperty:] + 538
4 Foundation 0x020431f4 -[NSObject(NSKeyValueObserverRegistration) removeObserver:forKeyPath:] + 105
5 Foundation 0x02043118 -[NSObject(NSKeyValueObserverRegistration) removeObserver:forKeyPath:context:] + 172
6 Rally 0x00005ac1 -[CustomCell dealloc] + 353
7 UIKit 0x01107b94 -[UIView release] + 89
8 CoreFoundation 0x025f7bf0 CFRelease + 272
9 CoreFoundation 0x0261716e -[__NSArrayM dealloc] + 142
10 libobjc.A.dylib 0x02406692 _ZN11objc_object17sidetable_releaseEb + 268
11 libobjc.A.dylib 0x02405e81 objc_release + 49
12 libobjc.A.dylib 0x02406ce7 _ZN12_GLOBAL__N_119AutoreleasePoolPage3popEPv + 537
13 CoreFoundation 0x02617878 _CFAutoreleasePoolPop + 24
14 CoreFoundation 0x0261c5d3 __CFRunLoopRun + 1971
15 CoreFoundation 0x0261b9d3 CFRunLoopRunSpecific + 467
16 CoreFoundation 0x0261b7eb CFRunLoopRunInMode + 123
17 GraphicsServices 0x036f85ee GSEventRunModal + 192
18 GraphicsServices 0x036f842b GSEventRun + 104
19 UIKit 0x010b5f9b UIApplicationMain + 1225
20 Rally 0x00006a6d main + 141
21 libdyld.dylib 0x02ef6701 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
I've double-checked (ctrl+f) that nowhere else are these methods called. So it seems that for any instance, there is precisely one addObserver (with unique context) and precisely one removeObserver (with that context)
Apologies all
Have just spotted my typo:
[self removeObserver:self
forKeyPath:#"currentLocation"
context:MyClassKVOContext];
should be
[[RA_LocationSingleton locationSingleton] removeObserver:self
forKeyPath:#"currentLocation"
context:MyClassKVOContext];