I want to send a string from one class to the other:
1) In class1, I add a property to hold the string:
#property (nonatomic, retain) NSString *str;
2) and a method to send back a string:
-(NSString *)sendBackStr:(NSString *)strURL
{
NSString *str = [[NSString alloc] stringWithString:strURL];
return str;
}
3) In class2, I add a property to hold the received string:
#property (nonatomic, retain) NSString *returnStr;
4) and the following code:
Class1 *c1 = [[Class1 alloc] init];
returnStr = [c1 sendBackStr:#"URL"];
But the program stops at returnStr = [c1 sendBackStr:#"URL"]; Any ideas about what's wrong with it?
stringWithString is a class method returning an autoreleased string. You should be calling it like this:
myProperty = [NSString stringWithString:strURL];
Here I assume your property does a copy, to increment the retain count on the autoreleased string that's returned from the stringWithString method. (Objects returned from alloc calls have a retain count of one and are not autoreleased.) It's more usual to give strings the copy property rather than the retain one - you usually just want your own copy of a string, not a shared reference to a string owned by someone else.
What I also can't understand is why you've written the code like this, unless it's just an example. In class 2, all you need to do is write
returnStr = [NSString stringWithString:#"URL"];
stringWithString: is a message that needs to be sent to the NSString class, not an instance of your class (returned via alloc).
The correct code should be:
-(NSString *)sendBackStr:(NSString *)strURL
{
return [NSString stringWithString:strURL];
}
You might want to familarize yourself more about the idioms around allocation, retention, and autoreleasing of pointers. If you wanted to alloc this string for some reason and return it from the sendBackStr: message, then you would probably want this code:
-(NSString *)sendBackStr:(NSString *)strURL
{
return [[[NSString alloc] initWithString:strURL] autorelease];
}
Related
Currently attempting to save an array that is populated according to which cells in a UITableView are chosen and saving this array in an instance of a seperate object. I am getting the array to populate just fine, however, my save method, which is an IBAction that is invoked by clicking on a Bar Button doesn't seem to be working. Here is some code:
-(IBAction)saveWorkout:(id)sender {
Workouts *new = [[Workouts alloc] init];
[new addNewWorkout:customWorkout];
[customWorkout removeAllObjects];
}
This code is from the first class.
And here is the code for my addNewWorkouts method in the Workouts class:
-(void)addNewWorkout:(NSMutableArray*)array {
NSMutableArray *temp = [[NSMutableArray alloc] init];
temp = array;
self.workoutList = temp;
[temp release];
}
Here is my "Workout.h"
#import <Foundation/Foundation.h>
#interface Workouts : NSObject {
NSString *workoutName;
NSMutableArray *workoutList;
NSString *description;
int *reps;
int *weights;
int *sets;
}
#property (nonatomic, retain) NSString *workoutName;
#property (nonatomic, retain ) NSString *description;
#property (nonatomic, retain) NSMutableArray *workoutList;
-(void)addNewWorkout:(NSMutableArray*)array;
#end
Before running this code, I get a Warning from Xcode saying that 'Workouts may not respond to 'addNewWorkouts.'
Anyone know what is causing this error? Once I build & run, I click on the Save button and the app crashes with a unrecognized selector sent to instance 0x3b04410 error.
You call [new addNewWorkouts:customWorkout]
when the method's selector is addNewWorkout: (note that there is no plural in the method name)
This will make a bad method call and result in a crash.
Also, there is a problem with the memory management of the addNewWorkout method.
1- NSMutableArray *temp = [[NSMutableArray alloc] init];
2- temp = array;
3- self.workoutList = temp;
4- [temp release];
You allocate a new NSMutableArray on line 1, then lose its reference on line 2 when you replace its pointer by 'array'. The allocation you just made is lost and the program will leak.
Then, on line 4, you send a release message to 'temp' which actually points to 'array', resulting in the release of the parameter that you received and not the temporary object.
Is there a reason whny you create a temporary array? You can just assign the property and make the property copy or retain it, depending on your needs.
After a ASIFormDataRequest , i create a temporary NSMutableArray *resultArray from the JSON then add it to a defined NSMutablearray *myData
-(void)viewDidLoad{
myData = [[NSMutableArray alloc] init];
//request that calls gotInfo method
}
-(void)gotInfo:(ASIFormDataRequest *)request{
NSString *responseString = [request responseString];
NSMutableArray *resultArray = [responseString yajl_JSON];
[myData addObject:resultArray];
}
-(IBAction)doSomethingWithData:(id)sender{
//something with myData
}
but when i try to call myData from outside of the gotInfo: method, i get bad access errors and when i inspect myData outside of the method, it shows a kern_protection_failure. So i'm guessing that outside of the method, the resultArray is obviously released, but it's also released from myData since the object inside myData is sharing the same memory location?
I also tried
-(void)gotInfo:(ASIFormDataRequest *)request{
NSString *responseString = [request responseString];
[myData addObject:[responseString yajl_JSON]];
}
How do I preserve myData??
in my header file:
#import <UIKit/UIKit.h>
#class ASIFormDataRequest;
#interface EventsTableController : UITableViewController <UITableViewDataSource>{
NSMutableArray *myData;
}
-(void)gotInfo:(ASIFormDataRequest *)request;
UPDATE:
so in the gbd, the myData is allocated as 0x5e96560 so i did
po 0x5e96560
and then i get the EXC_BAD_ACCESS with the reason being KERN_PROTECTION_FAILURE at address: 0x00000009
but if i do
po [[0x5e96560 objectAtIndex:0] objectForKey:#"key"]
then i get the value! whyyyyyy?
#property(nonatomic,retain) NSMutableArray *myData
and create the object
self.myData = [[NSMutableArray alloc] init];
and
// and i assume your resultArray is a mature NSMutableArray object
[self.myData addObject:resultArray];
The best way of using copy I can think of, is to always set NSString properties to "copy" instead of retain. That way you get more accurate readings from the Leaks instrument if you mess up and forget to release a string an object is holding onto. Other uses of copy need to be more carefully thought out.
NOTE : You are responsible to release myData after no use of that variable.
You dont really have any way to correctly access myData as you declare it as a member inside of EventsTableController, but you dont set the #property for it, and do not synthesize it either. By synthesizing it in your EventsTableController.m file you are telling xcode to generate the getter/setters you need to correctly touch myData, which is where your program seems to be failing. If you do this, this should solve your problem.
-Karoly
Except for the different name of your ivar (mienVar vs. myVar), I don't see a problem. Some other code must be releasing your ivar, or you are accessing it before viewDidLoad has the opportunity to actually create the array (I bet it is the latter).
I think you should put the code in viewDidLoad in your initialization method instead. Don't forget to release the array in dealloc.
You could, of course, also write your own myData getter method, doing lazy initialization, instead of creating it in the init method:
- (NSMutableArray *) myData
{
if (!myData)
myData = [[NSMutableArray alloc] init];
return myData;
}
Note that now, you should access self.myData if you want to use it.
I think the NSString yajl_JSON category can return an array or a dictionary - you might need to inspect the type of the result array on the line below as it may be an NSDictionary:
NSMutableArray *resultArray = [responseString yajl_JSON];
IF you are treating it as an array when its a dictionary that might be causing your problems.
(relevant code from the NSObject+YAJL category below)
YAJLDocument *document = [[YAJLDocument alloc] initWithData:data parserOptions:options error:error];
id root = [document.root retain];
[document release];
return [root autorelease];
(and in YAJLDocument object)
#interface YAJLDocument : NSObject <YAJLParserDelegate> {
(id root_; // NSArray or NSDictionary
Hey all. I know this question's been asked but I still don't have a clear picture of memory management in Objective-C. I feel like I have a pretty good grasp of it, but I'd still like some correct answers for the following code. I have a series of examples that I'd love for someone(s) to clarify.
Setting a value for an instance variable:
Say I have an NSMutableArray variable. In my class, when I initialize it, do I need to call a retain on it?
Do I do
fooArray = [[[NSMutableArray alloc] init] retain];
or
fooArray = [[NSMutableArray alloc] init];
Does doing [[NSMutableArray alloc] init] already set the retain count to 1, so I wouldn't need to call retain on it? On the other hand, if I called a method that I know returns an autoreleased object, I would for sure have to call retain on it, right? Like so:
fooString = [[NSString stringWithFormat:#"%d items", someInt] retain];
Properties:
I ask about the retain because I'm a bit confused about how #property's automatic setter works.
If I had set fooArray to be a #property with retain set, Objective-C will automatically create the following setter, right?
- (void)setFooArray:(NSMutableArray *)anArray {
[fooArray release];
fooArray = [anArray retain];
}
So, if I had code like this: self.fooArray = [[NSMutableArray alloc] init]; (which I believe is valid code), Objective-C creates a setter method that calls retain on the value assigned to fooArray. In this case, will the retain count actually be 2?
Correct way of setting a value of a property:
I know there are questions on this and (possibly) debates, but which is the right way to set a #property?
This?
self.fooArray = [[NSMutableArray alloc] init];
Or this?
NSMutableArray *anArray = [[NSMutableArray alloc] init];
self.fooArray = anArray;
[anArray release];
I'd love to get some clarification on these examples. Thanks!
According to Apple's Object Ownership Policy, any method that begins with the words alloc or new, or contains copy is owned by the caller.
To obtain ownership of an object, you must retain it.
So, in your first example, the retain is unnecessary because you already own the object.
The correct way to do this:
fooArray = [[NSMutableArray alloc] init];
Since autoreleased objects are owned by the current autorelease pool, you must call retain on them to gain ownership of them, so this example is correct:
fooString = [[NSString stringWithFormat:#"%d items", someInt] retain];
This would work fine as well:
self.fooString = [NSString stringWithFormat:#"%d items", someInt]; //retained by property setter
And for your last example using the property setter, this would be the correct way to do it:
NSMutableArray *anArray = [[NSMutableArray alloc] init];
self.fooArray = anArray;
[anArray release];
Instead of having to do the above, I'd suggest the following solution:
self.fooArray = [NSMutableArray arrayWithCapacity:10];
arrayWithCapacity: will return an autoreleased NSMutableArray, which is the retain-ed by the property setter method. :)
Ideally you would want to use the accessors whenever possible, especially when dealing with objects as they help avoid many memory issues. So even for instance variables, you should do:
self.fooArray = ...;
instead of
fooArray = ...;
The reason why you should declare properties for object instance variables is because the memory management is slightly more complicated, and recreating it by hand each time is tricky. The correct setter for a nonatomic, retained property would look like:
- (void)setFoo:(NSArray *)aFoo {
if (foo == aFoo) {
return;
}
NSArray *oldFoo = foo;
foo = [aFoo retain];
[oldFoo release];
}
You are right about the instance variable having a retain count of 2 when you do something like this (assuming foo is retained):
self.foo = [[NSMutableArray alloc] init];
The first retain count is coming from alloc, and the second one from your synthesized setter. Any of these should work:
// longer, explicit version, releases immediately (more efficient)
NSMutableArray *aFoo = [[NSMutableArray alloc] init];
self.foo = aFoo;
[aFoo release];
// autoreleased, not so bad unless you're a memory management freak
self.foo = [[[NSMutableArray alloc] init] autorelease];
// an even shorter version of the above
self.foo = [NSMutableArray array];
To create private properties, you can declare them as a class extension in the .m implementation file. To give an example, consider a simple Person object, which has a name, and a boolean property didSave which simply indicates whether the object has been saved to some database or not. Since we don't want to expose this to the outside world, but still keep the benefits of properties inside the implementation file, we can create the header file will all instance variables (public, private, protected) and only public properties:
// Person.h
#interface Person {
NSString *name;
#private
BOOL didSave;
}
#property (nonatomic, retain) NSString *name;
#end
But declare private properties inside the implementation:
// Person.m
// property is declared as a class extension, making it
// invisible to the outside world.
#interface Person ()
#property BOOL didSave;
#end
#implementation
// synthesize as normal
#synthesize name, didSave;
#end
First of all, with this line:
fooArray = [[NSMutableArray alloc] init];
fooArray will automatically have a retain count of 1.
Second, yes, it's 2. And your guess on the setter implementation is correct.
Third, the latter one is right
I have a singleton class with this code:
manager.h
#interface Manager : NSObject {
NSString *jobsLimit;
NSMutableDictionary *jobTitles;
}
#property (nonatomic, retain) NSString *jobsLimit;
#property (nonatomic, assign) NSMutableDictionary *jobTitles;
#implementation Manager
#synthesize jobsLimit;
#synthesize jobTitles;
+ (id)sharedManager {
#synchronized(self) {
if(shared == nil)
shared = [[super allocWithZone:NULL] init];
}
return shared;
}
- (id)init {
if (self = [super init]) {
jobsLimit = [[NSString alloc] initWithString:#"50"];
jobTitles = [[NSMutableDictionary alloc] init];
}
return self;
}
Then in the code i'm assigning these variables like this:
self.jobsLimit = [NSString stringWithFormat:#"%d", progressAsInt];
[self.jobTitles addEntriesFromDictionary:anotherDictionary];
- (void)dealloc {
[super dealloc];
[jobsLimit release];
[jobTitles release];
}
Now my question is this code correct? Is the assignment correct?
I'm very confused with when to use alloc and/or retain. Do I need to use alloc if my property is already retained? and If I use alloc should my property be assign?
What will be the reference count now for these variables and will they be dealloc'd/under-dealloc'd when the dealloc is called?
Also for singleton classes do I need to initialize my ivars as in the init method above or I do not have to.
I'd appreciate if someone can help me clear this confusion out and thanks in advance.
Regards,
Your code actually looks correct, but perhaps some explanation is in order, since it sounds like you're a little unsure.
When you assign to a property that has retain semantics using the "." syntax, the accessor method calls retain. The "." syntax is just shorthand for invoking the accessor method, so
self.jobsLimit = [NSString stringWithFormat:#"%d", progressAsInt];
is exactly the same as
[self setJobsLimit:[NSString stringWithFormat:#"%d", progressAsInt]];
That works out to:
create an (autoreleased) string with a numeric value
retain the string (you now own it) and assign it to jobsLimit
If, on the other hand, you assign to the iVar directly (not using the "."-accessor), the setter method is not called. For example:
jobsLimit = [[NSString alloc] initWithString:#"50"];
That is:
allocate a string (you own it), with value "50"
assign it to jobsLimit
Either way, you now own the string referred to by jobsLimit, and are responsible for eventually releasing it (e.g., in your dealloc method).
I guess you need a lot of this : IOS Memory Management
and a bit of : What should my Objective-C singleton look like?
good lectures !
I just spent the last 3 hours trying to figure out this error. I would like someone to explain it to me so I don't do it again.
I assigned an NSString instance variable without using "self". When the class ("self") released, I received a "bad access" error. I have done this exact same thing in another class with the same variable declarations and do not have this error. Below is my code. I commented out the line that broke and the line below fixes it. But I don't understand why... Notice that there are other instance variables that do not cause this problem. Should I always use the "self" reserved word when assigning instance variables? Please let me know.
declarations
#property (nonatomic, readonly, assign) int IID;
#property (nonatomic, assign) int ProfileIID;
#property (nonatomic, retain) NSDate *NoteDate;
#property (nonatomic, copy) NSString *NoteText;
code snippet
// the default date format is Year-Month-Day
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:kDateFormat];
IID = sqlite3_column_int(selectstmt, 0);
ProfileIID = sqlite3_column_int(selectstmt, 1);
// notice this does not cause a memory error
NoteDate = [[df dateFromString: [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)]] retain];
// the following may be NULL. Checking using the sqlite3_column_text method
const char *columnText = (const char *)sqlite3_column_text(selectstmt, 3);
if(columnText != NULL)
{
// this causes a memory error
//NoteText = [NSString stringWithUTF8String: columnText ];
// this does not cause memory error
self.NoteText = [NSString stringWithUTF8String: columnText ];
}
The reason that
NoteDate = [[df dateFromString: [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)]] retain];
is fine is because you retain the variable. Since you do not allocate the string, but call stringWithUTF8String on NSString, you do not take ownership of the variable, and so the string returned to you is autoreleased. However, since you retain it, this does not cause problems.
If variables are returned autoreleased, then they are released when the autorelease pool is drained, which occurs at the end of each event (see more on autorelease pools). This is no good with an instance variable, because it needs to stick around after the current event.
When you assign the variable by:
NoteText = [NSString stringWithUTF8String: columnText];
Your setter method is not invoked, so the returned string (which, again, is autoreleased) is not retained, and so is released by the autorelease pool at the end of the event.
Calling it as:
self.NoteText = [NSString stringWithUTF8String: columnText];
does retain the string, since the line is another way of writing:
[self setNoteText:[NSString stringWithUTF8String: columnText]];
which invokes your setter method and retains the variable, preventing it from being released at the end of the current event.
Assigning NoteText from within a class method doesn't invoke the synthesized setter method, it sets the instance variable directly. This means your string isn't being retained (or copied, in the case of your setter), and the crash is when trying to release an object which has already been released. Do this:
self.NoteText = [NSString stringWithUTF8String: columnText ];
This will call your setter, and all will be well.
Edit:
Just to be clear, this is true for all ivars.
myVariable = someValue; // Sets the ivar directly.
self.myVariable = someValue; // calls [self setMyVariable].
This confusion between ivar and setter methods is why I never name my setters and my ivars the same.
Apple typically names its ivars starting with an underscore (_), for example NoteText. In my case, I've taken to having a prefix of i for ivars. For example:
NSString* i_name;
#property (nonatomic, copy) NSString* name;
#synthesize name = i_name;
That way you can easily tell the difference between an ivar assignment:
i_name = [[whatever title] retain];
and a setter method call
self.name = [whatever title]; // Equivalent to [self setName:[whatever title]
The setter, since it is defined with copy (or similarly for retain) will take ownership of the variable passed in and release ownership of the old value. The ivar assignment does none of that.
Note also that your propery names should start with a lower case letter or they will not be KVO compliant.