Error adding a child node - ios

I'm getting the following error trying to add enemy nodes to my scene. The error message is : Attemped to add nil node to parent: <SKNode> name:'(null)' position:{0, 0} accumulatedFrame:{{inf, inf}, {inf, inf}}
(
0 CoreFoundation 0x00007fff905a541c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff8a101e75 objc_exception_throw + 43
2 CoreFoundation 0x00007fff905a52cc +[NSException raise:format:] + 204
3 SpriteKit 0x00000001000cc754 -[SKNode addChild:] + 161
4 InvadersMacTest 0x0000000100011fe0 -[MapScene initWithSize:] + 3552
5 InvadersMacTest 0x00000001000042fb -[OpcionesMenu handleKeyEvent:keyDown:] + 875
6 InvadersMacTest 0x0000000100004514 -[OpcionesMenu keyUp:] + 100
7 SpriteKit 0x000000010008ded8 -[SKView keyUp:] + 67
8 AppKit 0x00007fff8ee90f71 -[NSWindow sendEvent:] + 3721
9 AppKit 0x00007fff8ee31ca2 -[NSApplication sendEvent:] + 3395
10 AppKit 0x00007fff8ec81a29 -[NSApplication run] + 646
11 AppKit 0x00007fff8ec6c803 NSApplicationMain + 940
12 InvadersMacTest 0x0000000100003902 main + 34
13 libdyld.dylib 0x00007fff8d75a5fd start + 1
The code used to add the node is the following, i'm not doing something exceptional or tricky, just create a rectangle which simulate an enemy.
SKScene method
self.almacenEnemigos = [[NSMutableArray alloc] initWithCapacity:kNumEnemigos];
for(int i = 0; i < kNumEnemigos; i++)
{
enemigo *nemesis = [[enemigo alloc] init];
[nemesis pintarEnemigo:CGPointMake(200+5*i, 200+5*i)];
[self.almacenEnemigos addObject:nemesis];
[self.world addChild:nemesis->cobra];
}
And the method pintarEnemigo in enemigo class:
#interface enemigo()
#property (nonatomic) SKSpriteNode *cobra;
#end
-(SKSpriteNode*)pintarEnemigo:(CGPoint) pos
{
self.cobra = [[SKSpriteNode alloc] initWithColor:[SKColor orangeColor]
size:CGSizeMake(80.0f, 60.0f)];
self.cobra.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:25];
self.cobra.physicsBody.dynamic = YES;
self.cobra.position = CGPointMake(pos.x, pos.y);
self.cobra.name = #"Pulpo";
return self->cobra;
}
and enemigo.f file as demanded:
#interface enemigo : personaje
{
#public
SKSpriteNode *cobra;
}
-(id)init;
-(SKSpriteNode*)pintarEnemigo:(CGPoint) pos;
-(BOOL)enviarMensaje;
-(BOOL)mensajeRecibido;

What is self->cobra? That's your bug. The value is nil. It's never set to the object you created a few lines earlier.
I'm pretty sure you meant to use self.cobra.
The -> operator exists in Objective-C but should pretty much never be used, except maybe once or twice in ten years of programming. You should definitely never use it on self, although it is syntactically correct.
Your class has two instance variables, one is cobra and the other is _cobra. You're setting a value to _cobra and then returning the value of cobra.
self.cobra will return access _cobra, while self->cobra will access cobra.
In your *.h file, this line is incorrect:
SKSpriteNode *cobra;
You have three options to fix it:
change it to be named _cobra, which is the correct name for #property cobra;
delete the line altogether, and then the compiler will created _cobra automatically for you.
add an #synthesize rule to the enigmo.m file telling the compiler to use cobra instead of _cobra (lookup the documentation for #synthesize to learn how).
Once you've done that, you need to change the return self->cobra line to either:
return self.cobra;
return _cobra;
return cobra;
Which one depends on what you do in the header file, but I suggest the first option, since that is the generally accepted best practice for obj-c programming.

What happens if you change:
#interface enemigo()
#property (nonatomic) SKSpriteNode *cobra;
#end
to
#interface enemigo()
#property (nonatomic,strong) SKSpriteNode *cobra;
#end

Related

NSManagedObject changes memory address?

I have a transient, transformable property set for my MO subclass [FeedItem], and in a category, I provide lazy loaded access:
- (id)images
{
if (!self.sImages) {
self.sImages = [[self.imageEntitiesClass alloc] initWithModel:self];
}
return self.sImages;
}
- (void)setImages:(id)images
{
self.sImages = images;
}
Now, within -[FeedItem.managedObjectContext performBlock:] I call -[FeedItem prefetchImages]. What that does, is performs the following call stack:
-[FeedItem prefetchImages]
-[FeedItemImages avatar]
-[FeedItem avatarURL]
- MULTI-THREAD ASSERTION
Within -[FeedItemImages avatar] method, I call self.model.avatarURL, but by checking the debugger, self.model.managedObjectContext is different from the encapsulating MOC, so it makes sense that the assertion is triggered .. but, why is the MOC different? I explicitly pass self in the -[FeedItemImages init], so they should be the same object?
To confirm this issue, I have disabled the caching, and returned a new object every time, and the app worked great:
- (id)images
{
#warning TODO - underlying object is changing randomly?
/** For some weird reason, when we cache image entities, then attempt to
* retrieve an image, we sometimes trigger a multithreading assertions
* breakpoint. Debugger shows the owner of the image entity is different
* from the model the image entity is referencing ¯\_(ツ)_/¯
*
* Possible solutions:
* The Bad:
* Current solution. Easy, but very ineffecient.
* The Ugly:
* Cache the image entities object privately, and expose a different
* property that reassigns self every time.
* The Good:
* Firgure out when the object mutates (awake from fetch, or some other
* callback of CoreData) and invalidate the object there.
*/
return [[self.imageEntitiesClass alloc] initWithModel:self];
}
This was working perfectly when we had the root MOC as main, and created children MOC on the fly to perform object mapping.
backtrace:
frame #0: [...] CoreData`+[NSManagedObjectContext __Multithreading_Violation_AllThatIsLeftToUsIsHonor__] + 4
frame #1: [...] CoreData`_sharedIMPL_pvfk_core + 221
* frame #2: [...] Telly`Telly.TLYUserImages.feedAction.getter : Telly.TLYImageEntity(self=0x00007f84ca5cf6c0) + 416 at TLYUserImages.swift:26
frame #3: [...] Telly`#objc Telly.TLYUserImages.feedAction.getter : Telly.TLYImageEntity + 34 at TLYUserImages.swift:0
frame #4: [...] Foundation`-[NSObject(NSKeyValueCoding) valueForKey:] + 251
frame #5: [...] Foundation`-[NSArray(NSKeyValueCoding) valueForKey:] + 437
frame #6: [...] Foundation`-[NSObject(NSKeyValueCoding) valueForKeyPath:] + 245
frame #7: [...] Foundation`-[NSArray(NSKeyValueCoding) valueForKeyPath:] + 435
frame #8: [...] Foundation`-[NSObject(NSKeyValueCoding) valueForKeyPath:] + 261
frame #9: [...] Foundation`-[NSArray(NSKeyValueCoding) valueForKeyPath:] + 435
frame #10: [...] Foundation`-[NSObject(NSKeyValueCoding) valueForKeyPath:] + 261
frame #11: [...] Foundation`-[NSArray(NSKeyValueCoding) valueForKeyPath:] + 435
frame #12: [...] Telly`Telly.TLYMappingMeta.prefetch (target=AnyObject at 0x000000011e8ac858, self=0x00007f84ca423040)(forTarget : Swift.AnyObject) -> () + 361 at TLYMappingMeta.swift:75
frame #13: [...] Telly`#objc Telly.TLYMappingMeta.prefetch (Telly.TLYMappingMeta)(forTarget : Swift.AnyObject) -> () + 54 at TLYMappingMeta.swift:0
frame #14: [...] Telly`-[TLYMapTask _tag:with:using:in:](self=0x00007f84cecd64f0, _cmd=0x000000010aa12ee9, items=0x00007f84ca6d12e0, feedId=0x00007f84ce81ddf0, mapMeta=0x00007f84ca423040, moc=0x00007f84c9c89500) + 179 at TLYMapTask.m:42
frame #15: [...] Telly`__39-[TLYMapTask _map:toMOC:sync:callback:]_block_invoke(.block_descriptor=<unavailable>) + 1920 at TLYMapTask.m:127
frame #16: [...] CoreData`developerSubmittedBlockToNSManagedObjectContextPerform + 201
frame #17: [...] libdispatch.dylib`_dispatch_client_callout + 8
frame #18: 0x00000001107a76a7 libdispatch.dylib`_dispatch_queue_drain + 2176
frame #19: 0x00000001107a6cc0 libdispatch.dylib`_dispatch_queue_invoke + 235
frame #20: 0x00000001107aa3b9 libdispatch.dylib`_dispatch_root_queue_drain + 1359
frame #21: 0x00000001107abb17 libdispatch.dylib`_dispatch_worker_thread3 + 111
frame #22: 0x0000000110b2d637 libsystem_pthread.dylib`_pthread_wqthread + 729
frame #23: 0x0000000110b2b40d libsystem_pthread.dylib`start_wqthread + 13
ImageEntities.swift
import Foundation
/** Each model object is composed of an imageEntities subclass that
* holds the image entities associated with that model.
*/
class TLYImageEntities: NSObject {
unowned let model: AnyObject
init(model: AnyObject) {
self.model = model
}
}
Example subclass of ImageEntities. Notice how self.user.avatarURL access the MO subclass property:
TLYUserImages:
import Foundation
class TLYUserImages: TLYImageEntities {
var user: TVUser {
return model as! TVUser
}
lazy var profileHeader: TLYImageEntity = TLYImageEntity(
listItem: self.user,
imageURL: self.user.avatarURL,
formatName: TLYImageFormatUserProfileHeader,
processor: TVImageProcessor.avatarProcessor()
)
...
}
TVUser+Aggregator, which provides the image entities class:
#implementation TVUser (Aggregator)
- (Class)imageEntitiesClass
{
return [TLYUserImages class];
}
...
#end
Because initWithModel:self is called on an instance of a managed object subclass, it seems logical that the address changes. self refers to the instance variable, so whenever you call this with a different variable, the content of the arguments of your cryptic method will also be different. Perhaps your clever method to just insert a new object is a little bit too clever.
Maybe you should dispense with this hardly readable and evidently buggy method and do something more intuitive and straight-forward, like a class method that takes a context and returns a new object inserted into that context.
I would concur with the time-honored quote of the previous poster, Marcus S. Zarra:
The mantra is the same. Keep the code simple. Do not be clever, do not be lazy. Do it right and it will be easy to maintain. Be clever or lazy and you are only punishing yourself and your users.
What does [[self.imageEntitiesClass alloc] initWithModel:self] do? Specifically was does -initWithModel: do? It is very strange to be calling an alloc init like that.
Looking into that method will help to determine what this interesting issue is.

iOS 8.1 with ZXING error ARC forbids explicit message send of 'autorelease'

I developed a DataMatrix Reader for Android with ZXING, and works fine, now I'm working in the version of iOS, but I have this errors when I want to use the library inside my project:
iOS SDK 8.1 and Library
ZXING: https://github.com/TheLevelUp/ZXingObjC
I use the COCOAPODS:
platform :ios, '7.0'
pod 'ZXingObjC', '~> 3.0'
I implemented the library in my project with Cocoapods, now I want to use in my App like this:
#import "ViewController.h"
#import "ZXingObjC.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)scanBarcode:(id)sender {
CGImageRef imageToDecode; // Given a CGImage in which we are looking for barcodes
ZXLuminanceSource *source = [[[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode] autorelease];
ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
NSError *error = nil;
// There are a number of hints we can give to the reader, including
// possible formats, allowed lengths, and the string encoding.
ZXDecodeHints *hints = [ZXDecodeHints hints];
ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
ZXResult *result = [reader decode:bitmap
hints:hints
error:&error];
if (result) {
// The coded result as a string. The raw data can be accessed with
// result.rawBytes and result.length.
NSString *contents = result.text;
// The barcode format, such as a QR code or UPC-A
ZXBarcodeFormat format = result.barcodeFormat;
} else {
// Use error to determine why we didn't get a result, such as a barcode
// not being found, an invalid checksum, or a format inconsistency.
}
}
#end
but I have this error:
DataMatrixReader/ViewController.m:32:99: ARC forbids explicit message
send of 'autorelease'
DataMatrixReader/ViewController.m:32:99: 'autorelease' is unavailable:
not available in automatic reference counting mode
concretly in this line:
ZXLuminanceSource *source = [[[ZXCGImageLuminanceSource alloc]
initWithCGImage:imageToDecode] autorelease];
Help from "iamnichols"...and after the change the line:
ZXLuminanceSource *source = [[[ZXCGImageLuminanceSource alloc]
initWithCGImage:imageToDecode] autorelease];
to
ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc]
initWithCGImage:imageToDecode];
Error:
: CGBitmapContextGetData: invalid context 0x0. This is a
serious error. This application, or a library it uses, is using an
invalid context and is thereby contributing to an overall degradation
of system stability and reliability. This notice is a courtesy: please
fix this problem. It will become a fatal error in an upcoming update.
2014-12-15 12:12:36.122 DataMatrixReader[18838:412778] * Terminating
app due to uncaught exception 'NSInvalidArgumentException', reason:
'Both dimensions must be greater than 0'
* First throw call stack: ( 0 CoreFoundation 0x0000000102626f35 exceptionPreprocess + 165 1 libobjc.A.dylib
0x00000001022bfbb7 objc_exception_throw + 45 2 DataMatrixReader
0x0000000100f09507 -[ZXBitMatrix initWithWidth:height:] + 231 3
DataMatrixReader 0x0000000100f51b7d
-[ZXGlobalHistogramBinarizer blackMatrixWithError:] + 141 4 DataMatrixReader 0x0000000100f530b0
-[ZXHybridBinarizer blackMatrixWithError:] + 816 5 DataMatrixReader 0x0000000100f068ab -[ZXBinaryBitmap blackMatrixWithError:] + 139 6
DataMatrixReader 0x0000000100fa43b2
-[ZXQRCodeReader decode:hints:error:] + 130 7 DataMatrixReader 0x0000000100f63d04 -[ZXMultiFormatReader decodeInternal:error:] + 548
8 DataMatrixReader 0x0000000100f62ade
-[ZXMultiFormatReader decode:hints:error:] + 142 9 DataMatrixReader 0x0000000100ef1df2 -[ViewController scanBarcode:] + 322 10 UIKit
0x0000000102a148be -[UIApplication sendAction:to:from:forEvent:] + 75
11 UIKit 0x0000000102b1b410
-[UIControl _sendActionsForEvents:withEvent:] + 467 12 UIKit 0x0000000102b1a7df -[UIControl touchesEnded:withEvent:] + 522 13
UIKit 0x0000000102a5a308 -[UIWindow
_sendTouchesForEvent:] + 735 14 UIKit 0x0000000102a5ac33 -[UIWindow sendEvent:] + 683 15 UIKit
0x0000000102a279b1 -[UIApplication sendEvent:] + 246 16 UIKit
0x0000000102a34a7d _UIApplicationHandleEventFromQueueEvent + 17370 17
UIKit 0x0000000102a10103
_UIApplicationHandleEventQueue + 1961 18 CoreFoundation 0x000000010255c551
__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17 19 CoreFoundation 0x000000010255241d
__CFRunLoopDoSources0 + 269 20 CoreFoundation 0x0000000102551a54 __CFRunLoopRun + 868 21 CoreFoundation
0x0000000102551486 CFRunLoopRunSpecific + 470 22 GraphicsServices
0x0000000104bc09f0 GSEventRunModal + 161 23 UIKit
0x0000000102a13420 UIApplicationMain + 1282 24 DataMatrixReader
0x0000000100ef2343 main + 115 25 libdyld.dylib
0x00000001058a3145 start + 1 ) libc++abi.dylib: terminating with
uncaught exception of type NSException (lldb)
Now the question is somebody tried to integrate the ZxingObjC in iOS 8.1?
I think your project is using ARC but ZXING library isn't. In that case go to path 'Target -> Build Phases -> Compile Sources' in ZXING library. Double click on each .m file and enter '-fno-objc-arc' in popped dialog box. In this way those files will be excluded from ARC
If you project is using ARC (Automatic Reference Counting) then you don't need to make autorelease calls as it is done for you.
Change
ZXLuminanceSource *source = [[[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode] autorelease];
to
ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode];
Further information about ARC can be found on the iOS Developer Library
This works perfectly for me:
Getting Started in the readme.md didn’t work so I had to do the following steps to make it work.
copy the whole folders into your working project’s sub-folder.
and drag/add ZXingObjC.xcodeproj file to “<your working project>”.
make sure tick create folder references for any added folders option when prompted.
then, go to your project’s Target > Build Phases
under Target Dependencies, add ZXingObjC-iOS (ZXingObjC)
under Link Binary With Libraries, add libZXingObjC-iOS.a
under the same category, add the following 6 frameworks
AVFoundation.framework
CoreGraphics.framework
CoreMedia.framework
CoreVideo.framework
ImageIO.framework
QuartzCore.framework
Source in: http://sagage.com/?p=55
My test in a direct device Iphone 4s were good, perhaps is not the best device to test that, Iphone 4s has not a "AutoFocus" feature, very important for work with this barcodes.
hope this saves your day.

NSGenericException reason Collection <NSConcreteMapTable: xxx>

this is the error that i see when present SKScene, this error occurs randomly and are not able to replicate
* Terminating app due to uncaught exception 'NSGenericException', reason: '* Collection < NSConcreteMapTable: 0x1459da60 > was mutated while being enumerated.'
what's happen?
tell me if you need any other info
thanks
EDIT:
*** First throw call stack:
(
0 CoreFoundation 0x025601e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x022298e5 objc_exception_throw + 44
2 CoreFoundation 0x025efcf5 __NSFastEnumerationMutationHandler + 165
3 Foundation 0x01e47f03 -[NSConcreteMapTable countByEnumeratingWithState:objects:count:] + 66
4 CoreFoundation 0x0253d77f -[__NSFastEnumerationEnumerator nextObject] + 143
5 SpriteKit 0x01d009f2 +[SKTextureAtlas(Internal) findTextureNamed:] + 232
6 SpriteKit 0x01cf709c __26-[SKTexture loadImageData]_block_invoke + 1982
7 SpriteKit 0x01d34d09 _Z14SKSpinLockSyncPiU13block_pointerFvvE + 40
8 SpriteKit 0x01cf6898 -[SKTexture loadImageData] + 228
9 SpriteKit 0x01cf65d9 __51+[SKTexture preloadTextures:withCompletionHandler:]_block_invoke + 241
10 libdispatch.dylib 0x02b117b8 _dispatch_call_block_and_release + 15
11 libdispatch.dylib 0x02b264d0 _dispatch_client_callout + 14
12 libdispatch.dylib 0x02b14eb7 _dispatch_root_queue_drain + 291
13 libdispatch.dylib 0x02b15127 _dispatch_worker_thread2 + 39
14 libsystem_c.dylib 0x02de1e72 _pthread_wqthread + 441
15 libsystem_c.dylib 0x02dc9daa start_wqthread + 30
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I get the same exception on occasion. It's been around for a while and I've been trying to pinpoint it for weeks.
My suspicion is that it may occur due to preloading textures, either manually or triggered automatically by Sprite Kit while at the same time some other code causes textures to be loaded or accessed.
I have reduced my preloadTextures: calls to a single one but I still get the issue, just less often. I have tried to performSelector:onMainThread: whenever I run a selector that accesses or loads images (or just might internally) from within a completionBlock or other code that runs on a different thread.
I haven't had this crash the entire day today after I moved my user interface code to the main thread (it was called from a completion handler). I can't say 100% for sure whether this fixed it though.
I hope this helps a little. There's definitely something finicky going on, and if you do po 0x1459da60 (in lldb's command window, using the address provided by the exception) you'll see that it is the SKTextureAtlas texture list that is being modified. I hope that helps you pinpoint where the issue is coming from on your side.
From what I can tell this a sprite kit bug in the sprite kit method:
preloadTextures: withCompletionHandler:
The only way I was able to fix this was by removing this method completely.
According to apple docs the textures also get loaded if you access the size property.
So my workaround is just to do exactly that:
for (SKTexture *texture in self.texturesArray) {
texture.size;
}
It's not pretty but it works!
I had the same problem, when I tried to preload two simple animations. I tried to preload the animations in a dictionary and have them ready to be called via a string key. Here is what I tried
-(void)setupAnimDict {
animDict = [[NSMutableDictionary alloc] init];
[animDict setObject:[self animForName:#"blaze" frames:4] forKey:#"blaze"];
[animDict setObject:[self animForName:#"flame" frames:4] forKey:#"flame"];
}
-(SKAction *)animForName:(NSString *)name frames:(int)frames {
NSArray *animationFrames = [self setupAnimationFrames:name base:name num:frames];
SKAction *animationAction = [SKAction animateWithTextures:animationFrames timePerFrame:0.10 resize:YES restore:NO];
return [SKAction repeatActionForever:animationAction];
}
-(NSArray *)setupAnimationFrames:(NSString *)atlasName base:(NSString *)baseFileName num:(int)numberOfFrames {
[self preload:baseFileName num:numberOfFrames];
NSMutableArray *frames = [NSMutableArray arrayWithCapacity:numberOfFrames];
SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:atlasName];
for (int i = 0; i < numberOfFrames; i++) {
NSString *fileName = [NSString stringWithFormat:#"%#%01d.png", baseFileName, i];
[frames addObject:[atlas textureNamed:fileName]];
}
return frames;
}
-(void)preload:(NSString *)baseFileName num:(int)numberOfFrames {
NSMutableArray *frames = [NSMutableArray arrayWithCapacity:numberOfFrames];
for (int i = 0; i < numberOfFrames; i++) {
NSString *fileName = [NSString stringWithFormat:#"%#%01d.png", baseFileName, i];
[frames addObject:[SKTexture textureWithImageNamed:fileName]];
}
[SKTexture preloadTextures:frames withCompletionHandler:^(void){}];
}
When I called the setupDict method I sometimes got the same error as you. The problem was that preloading of my two animations run into each other. I got rid of the error by changing the
[SKTexture preloadTextures:frames withCompletionHandler:^(void){}];
to
if ([baseFileName isEqualToString:#"blaze"]) {
[SKTexture preloadTextures:frames withCompletionHandler:^{
[self setupFlame];
}];
} else {
[SKTexture preloadTextures:frames withCompletionHandler:^(void){}];
}
so that the first preloading was done before I attempted to preload the other.
I don't know if this is your problem, but if it is let us know.
Same thing still happening for me in Xcode 6.3 beta / Swift 1.2. Here is a temporary fix that has worked for me.
SKTextureAtlas.preloadTextureAtlases([SKTextureAtlas(named: "testAtlas")], withCompletionHandler: {
dispatch_async(dispatch_get_main_queue(), {
handler()
})
})
I actually wrapped this in a function so that all preloads route through it. That way if it gets fixed on the SpriteKit side, or if there are major flaws with this approach, I can remove the dispatch.

Does dealloc call the setter of properties to nil them?

When iOS memory management deallocates a given object, does the process of deallocation nil the instance variables of any properties it may have, via setter methods?
No. We can verify this experimentally with the following program:
#import <Foundation/Foundation.h>
#interface CVObject : NSObject
#property (nonatomic) NSNumber *number;
#end
#implementation CVObject
- (void)setNumber:(NSNumber *)number
{
NSLog(#"setting number to %#", number);
_number = number;
}
- (void)dealloc
{
NSLog(#"deallocating");
}
#end
void doSomething()
{
CVObject *object = [[CVObject alloc] init];
object.number = #3;
}
int main(int argc, const char * argv[])
{
#autoreleasepool {
doSomething();
}
return 0;
}
The output upon running it is:
setting number to 3
deallocating
By adding another property of type CVObject* to the class, and putting a breakpoint in dealloc, we can observe the stack trace at the second object's deallocation:
* thread #1: tid = 0x2203, 0x0000000100001a77 DoesDeallocUseProperties`-[CVObject dealloc](self=0x0000000102501da0, _cmd=0x00007fff934f508b) + 23 at main.m:36, stop reason = breakpoint 1.1
frame #0: 0x0000000100001a77 DoesDeallocUseProperties`-[CVObject dealloc](self=0x0000000102501da0, _cmd=0x00007fff934f508b) + 23 at main.m:36
frame #1: 0x0000000100001b4a DoesDeallocUseProperties`-[CVObject .cxx_destruct](self=0x0000000100103510, _cmd=0x000f6a00000f6a00) + 90 at main.m:20
frame #2: 0x00007fff90030fcc libobjc.A.dylib`object_cxxDestructFromClass(objc_object*, objc_class*) + 100
frame #3: 0x00007fff9002a922 libobjc.A.dylib`objc_destructInstance + 91
frame #4: 0x00007fff9002afa0 libobjc.A.dylib`object_dispose + 22
frame #5: 0x0000000100001aa4 DoesDeallocUseProperties`-[CVObject dealloc](self=0x0000000100103510, _cmd=0x00007fff934f508b) + 68 at main.m:37
frame #6: 0x0000000100001c5c DoesDeallocUseProperties`doSomething + 268 at main.m:48
frame #7: 0x0000000100001c94 DoesDeallocUseProperties`main(argc=1, argv=0x00007fff5fbffa80) + 36 at main.m:54
frame #8: 0x00007fff951997e1 libdyld.dylib`start + 1
It's clear from the trace no property setters or getters are being used.
Now, why might this be so? It's important to understand that properties and instance variables have no inherent connection. The names can vary independently. It is perfectly legal to have a property called name, for instance, and an instance variable _name, and implement setters and accessors for name that do not actually touch the instance variable _name. If ARC relied on properties, such a case would be disastrous.
No it simple sends a release message to all instance variables.
This can be observed with a simple test, assuming myProp is a strong property:
-(void)dealloc
{
NSLog(#"deallocing");
}
-(void)setMyProp:(MyClass *)prop
{
NSLog(#"setting my prop: %#", prop);
}
You will see that the setMyProp: method is not invoked as a result of a deallocation.
You can in theory manually call setMyProp: from the overridden dealloc method but it is advised that caution be taken: Calling a method on self while in dealloc

Xcode 4 and "SIGABRT" error? (only for iphone though)

I'm new to ios development and to stackoverflow. I did try searching both stackoverflow and google before posting.
I built a simple little app, originally just left it an iphone only app, but decided to make it universal in the end. I, stupidly, was messing around when i was getting to know xcode 4 and switched it to universal and then back again so i had to recopy the project and do it again. This time i started it with a universal app. (Not when i created it but after i went to project and selected it there) It created the ipad folder and mainwindow-ipad.xib file but was empty of course since i didn't do anything yet. I had it set up as a tabbed based app so my iphone version had firstview and secondview nib files also, but the ipad version didn't. I set it all up in iphone version first and it worked fine. I then went and laid down the ipad version (i did eliminate the second tab from mainwindow-ipad because i didn't need it)
i then went and created a new nib file and placed it in the ipad folder along with "main-ipad.h" and "main-ipad.m". I copied my code and connected everything and it runs fine on ipad simulator but now when i try and run iphone simulator i get "SIGABRT error. I took a screen shot of it. I don't fully understand objective-c so i was hoping someone can help me? I can post any code or whatever you might need to help me with this error so just ask.
Appreciate any help and suggestions you may have!
Thanks!
[Okay i would have posted image but I can't since I'm a new user, instead i posted the line highlighted and the output from xcode]
Code for file with error:
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil); //ERROR IS ON THIS LINE <-----
[pool release];
return retVal;
}
[OUTPUT]
2011-06-18 17:32:43.980 Price Assist[445:207] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x4e09cc0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key finallabel.'
*** Call stack at first throw:
(
0 CoreFoundation 0x00dc35a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f17313 objc_exception_throw + 44
2 CoreFoundation 0x00dc34e1 -[NSException raise] + 17
3 Foundation 0x00795677 _NSSetUsingKeyValueSetter + 135
4 Foundation 0x007955e5 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 285
5 UIKit 0x0021130c -[UIRuntimeOutletConnection connect] + 112
6 CoreFoundation 0x00d398cf -[NSArray makeObjectsPerformSelector:] + 239
7 UIKit 0x0020fd23 -[UINib instantiateWithOwner:options:] + 1041
8 UIKit 0x00211ab7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168
9 UIKit 0x000c7628 -[UIViewController _loadViewFromNibNamed:bundle:] + 70
10 UIKit 0x000c5134 -[UIViewController loadView] + 120
11 UIKit 0x000c500e -[UIViewController view] + 56
12 UIKit 0x00038d42 -[UIWindow addRootViewControllerViewIfPossible] + 51
13 Foundation 0x007955e5 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 285
14 UIKit 0x00048ff6 -[UIView(CALayerDelegate) setValue:forKey:] + 173
15 UIKit 0x0021130c -[UIRuntimeOutletConnection connect] + 112
16 CoreFoundation 0x00d398cf -[NSArray makeObjectsPerformSelector:] + 239
17 UIKit 0x0020fd23 -[UINib instantiateWithOwner:options:] + 1041
18 UIKit 0x00211ab7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168
19 UIKit 0x0001717a -[UIApplication _loadMainNibFile] + 172
20 UIKit 0x00017cf4 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 291
21 UIKit 0x00022617 -[UIApplication handleEvent:withNewEvent:] + 1533
22 UIKit 0x0001aabf -[UIApplication sendEvent:] + 71
23 UIKit 0x0001ff2e _UIApplicationHandleEvent + 7576
24 GraphicsServices 0x00ffc992 PurpleEventCallback + 1550
25 CoreFoundation 0x00da4944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
26 CoreFoundation 0x00d04cf7 __CFRunLoopDoSource1 + 215
27 CoreFoundation 0x00d01f83 __CFRunLoopRun + 979
28 CoreFoundation 0x00d01840 CFRunLoopRunSpecific + 208
29 CoreFoundation 0x00d01761 CFRunLoopRunInMode + 97
30 UIKit 0x000177d2 -[UIApplication _run] + 623
31 UIKit 0x00023c93 UIApplicationMain + 1160
32 Price Assist 0x000029a9 main + 121
33 Price Assist 0x00002925 start + 53
)
terminate called after throwing an instance of 'NSException'
iPhone FirstView nib file .h code:
#interface FirstViewController : UIViewController {
IBOutlet UITextField *dollarinput;
IBOutlet UITextField *centsinput;
IBOutlet UIButton *combinevalue;
IBOutlet UITextField *percentoffinput;
IBOutlet UILabel *discountlabel;
IBOutlet UILabel *finallabel;
}
- (IBAction)calculate:(id)sender;
- (IBAction)backgroundTouched:(id)sender;
- (IBAction)autonext:(id)sender;
iPhone FirstView nib file .m code:
//
// FirstViewController.m
// Price Assist
//
// Created by Dustin Schreiber on 6/15/11.
// Copyright 2011 TheTechSphere.com. All rights reserved.
//
#import "FirstViewController.h"
#implementation FirstViewController
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload
{
[percentoffinput release];
percentoffinput = nil;
[discountlabel release];
discountlabel = nil;
[finallabel release];
finallabel = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[percentoffinput release];
[discountlabel release];
[finallabel release];
[super dealloc];
}
- (IBAction)calculate:(id)sender {
if ([centsinput.text length] == 0){
centsinput.text = #"00";
}
if ([dollarinput.text length] == 0){
dollarinput.text = #"00";
}
if ([percentoffinput.text length] == 0){
percentoffinput.text = #"00";
}
double cDollars = [dollarinput.text doubleValue];
double cCents = [centsinput.text doubleValue];
double percentoff = [percentoffinput.text doubleValue] / 100;
NSString *ccDollars = [[NSNumber numberWithFloat:cDollars] stringValue];
NSString *ccCents = [[NSNumber numberWithFloat:cCents] stringValue];
NSString *placeholder = [NSString stringWithFormat:#"%#.%#", ccDollars, ccCents];
double combined = [placeholder doubleValue];
double discount = combined * percentoff;
NSString *discountholder2 =[NSString stringWithFormat:#"%.2f", discount];
discountlabel.text = discountholder2;
double newprice = (combined - discount);
NSString *str = [NSString stringWithFormat:#"%.2f", newprice];
finallabel.text = str;
dollarinput.text = ccDollars;
centsinput.text = ccCents;
percentoffinput.text = [[NSNumber numberWithFloat:percentoff] stringValue];
}
-(IBAction)backgroundTouched:(id)sender
{
[dollarinput resignFirstResponder];
[centsinput resignFirstResponder];
[percentoffinput resignFirstResponder];
}
- (IBAction)autonext:(id)sender {
if ([centsinput.text length ] >= 2) {
if ([centsinput.text length] > 2) {
centsinput.text = #"";
} else {
//next field
}
}
}
#end
Thanks again! If anyone has any suggestions for my code i'd love to here them! Like I said, I'm new to it and thats the only way i know to do this.
------------> If anyone wants, I'll upload the entire project folder. Just ask. Thank you guys for all the help. i'm a n00b with xcode so i haven't got it all down yet.
Project Zipped
Post some code where you use finallabel and try to debug your app so you can tell me the line just before the app crashes.
Option 2:
Try to set a BreakPoint in malloc_error_break so we can have more info about the error.
In XCode go to Run -> Show -> BreakPoints (or just cmd + option + B). Then double click to add a new symbol (symbolic breakpoint) and type in malloc_error_break then press enter.
Now run your app and paste your console text.
UPDATE If you need help http://developer.apple.com/library/mac/#recipes/xcode_help-breakpoint_navigator/articles/adding_a_symbolic_breakpoint.html
Check your connections inside your InterfaceBuilder, you may have it wrong with fianllabel.
Also check your Custom Class -> Class in your iphone XIB in your InterfaseBuilder
UPDATE
Go to Product -> Clean. Then Run.
The line UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); just means that an exception was thrown during the running of your program. This could range from a memory problem, to a simple runtime error. Look in the target debugger console; it will tell you where the error occurred.
Open "iOS Simulator" Menu in the upper left->Reset Content and Settings. Then quit the iOS simulator and Xcode, and then restart your computer. This will get rid of the other instance of the process.
This May work it's work for me...........
The problem is with your XIB file. This error generally occurs when your finalLabel is incorrectly hooked up or doesn't exist anymore. Check your connections in the Interface Builder once.
I also had this error. After spending so much time, I found how to fix it. First of all go the console and see where is the error (mine was related to storyboards and its code) The way I fixed my error was by going in story board. Below the iPhone screen, there will be small yellow button. Right click on it and you will see that is causing error. Delete(x) it if there is yellow error sign.
If this does not fix your error then try to make new project and then replace its blank files with old files of your old project. I had same error in very beginning and by doing this program run without any error.
Other people suggests by restarting your laptop and running it again, reseting the iOS simulator, or changing iOS debugger (however this does not work in latest x code since there is only one debugger)
Hope this helps

Resources