Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Basic Obj-C Question on Memory and Strings



--- On Thu, 8/7/08, Matt Keyes <email@hidden> wrote:

> -(void)foo {
>      SomeClass *cls = [[SomeClass alloc] init];
>      [cls DoTheStringThing:@"Here's a fun
> string."];
> 
>     //HERE IS THE QUESTION:
>     //This causes a halt in the debugging and will
> sometimes give a _BAD_ADDRESS or something... simply
> checking the NSString pointer causes it
>     //I am having a hard time I guess understanding Obj-C
> memory management b/c in traditional C/C++ this would be
> fine to do 
>     if(cls.someString)
>     {
>           self.txtMyTextBox.text = [[NSString alloc]
> cls.someString];
>     }
> }

This would not be fine in C++. The alloc/init pair is roughly equivalent to C++'s new operator. Here's a somewhat equivalent method in C++:

void foo() {
SomeClass *cls = new SomeClass;
if (cls.getSomeString()) {
string tempString = cls.getSomeString();
this.getTxtMyTextBox().setText((malloc(sizeof(string))).tempString());
}
}

You're trying to take a string property and send it as a message to an uninitialized object, and then take the result of this non-method and assign it to a property of another object. The odd thing is that it compiles at all. I suggest you reread the Objective-C memory management docs.

http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

You might also try working through some basic Cocoa tutorials to give you a feel for how Cocoa programming works before you set out on your own. Besides memory management, you seem a bit unclear on Obj-C's message syntax. It's unfamiliar, but not really that hard. If you take it slow for a little bit, I think everything will become clear pretty quickly.

Cheers,
Chuck


      
_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/email@hidden

This email sent to email@hidden

References: 
 >Basic Obj-C Question on Memory and Strings (From: Matt Keyes <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.