Objective c: setting an object attribute ; attribute not updating - iphone

Wow. I have had a total mental failure this morning stuck on this 101 problem.
In ViewController, I have this code. But after it executes, the value of [proposalInfo expanded] is still NO. Can somebody see what I'm doing wrong?
- (void)showFullProposal:(id) sender {
// update proposalinfo
ProposalInfo *proposalInfo = [self.proposalInfoArray objectAtIndex:index.section];
[proposalInfo setExpanded:YES];
}
The variables are declared as follows:
ViewController:
#interface ViewController()
#property (nonatomic, strong) NSMutableArray* proposalInfoArray;
#end
ProposalInfo.h:
#interface ProposalInfo : NSObject
#property (assign) BOOL expanded;
#end
ProposalInfo.m:
#synthesize expanded;
Please help!!

If you never alloc/init your proposalInfoArray array, you could experience behavior like this (i.e. get no error, but always get NO back because when you send a message to a nil object, you get nil back). If not precisely this, it's going to be something simple like that. Check proposalInfoArray and make sure it's not nil. Also check the proposalInfo object you got back, make sure it's not nil.
To illustrate your likely problem, this reproduces the behavior you describe (e.g. expanded looks like it's NO, regardless, but you still don't get any exception):
self.proposalInfoArray = nil; // This obviously won't work
[self.proposalInfoArray addObject:[[ProposalInfo alloc] init]];
ProposalInfo *proposalInfo = [self.proposalInfoArray objectAtIndex:0];
NSLog(#"before=%d", proposalInfo.expanded); // OK, IT'S "0"
proposalInfo.expanded = YES;
NSLog(#"after=%d", proposalInfo.expanded); // HEY, IT'S STILL "0" -- BAD!
Whereas this works properly:
self.proposalInfoArray = [[NSMutableArray alloc] init];
[self.proposalInfoArray addObject:[[ProposalInfo alloc] init]];
ProposalInfo * proposalInfo = [self.proposalInfoArray objectAtIndex:0];
NSLog(#"before=%d", proposalInfo.expanded); // OK, IT'S "0"
proposalInfo.expanded = YES;
NSLog(#"after=%d", proposalInfo.expanded); // HEY, IT'S NOW "1" -- GOOD!
In terms of how to identify these issues in the future, use NSAssert. We would have found this problem if we had the following line of code before the objectAtIndex line:
NSAssert(self.proposalInfoArray, #"proposalInfoArray must be initialized!");
or, after the objectForIndex:
NSAssert(proposalInfo, #"proposalInfo must not be nil!");
The nice thing about NSAssert statements is that you can put them in your code, and when you build for debugging, they help you find your program logic mistakes, but when you build your final release version, they're automatically omitted, making your code more efficient. So, use NSAssert liberally!

Imme, the following line seems to be strange:
ProposalInfo *proposalInfo = [self.proposalInfoArray objectAtIndex:index.section];
Actually, what do you have in your array, means in proposalInfoArray.
Have you checked your object?

Related

EXC_BAD_ACCESS when adding NSOperation to NSOperationQueue

I've been sitting on this error for hours now. I'm getting an EXC_BAD_ACCESS (code=2) on the line:
[self.downloadQueue addOperation:self.downloadOP];
I know it has to be related to memory conflicts, but I just can't find the problem. The class that manages the OperationQueues is a singleton, but i think thats not the problem.
Here's the shortened version of my .h file:
#interface GTMConnectionManager : NSObject{
}
#property (retain) GTMDownloadOperation *downloadOP;
#property (retain) NSOperationQueue *downloadQueue;
// it doesn't make a difference if I add 'nonatomic' to these properties
+ (GTMConnectionManager *)sharedConnectionManager;
-(void)downloadImageData:(NSMutableArray*)p_images andController:(UIViewController*)p_resultsController;
#end
And the important part of the .m file:
#import "GTMConnectionManager.h"
#implementation GTMConnectionManager
#synthesize downloadOP, downloadQueue;
+ (GTMConnectionManager *)sharedConnectionManager
{
static GTMConnectionManager * instance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
instance = [[super allocWithZone:nil] init];
});
return instance;
}
-(void)downloadImageData:(NSMutableArray*)p_images andController:(GTMResultsListViewController*)p_resultsController{
self.resultsController = p_resultsController;
[self.downloadQueue setMaxConcurrentOperationCount:2];
self.downloadQueue = [[[NSOperationQueue alloc]init]autorelease];
// it doesn't make a difference if I do this with or without 'autorelease'
for (int i = 0; i < [p_images count]; i++) {
GTMGeoImage *tmpImg = [p_images objectAtIndex:i];
self.downloadOP = [[[GTMDownloadOperation alloc]initWithImage:tmpImg]autorelease];
[self.downloadQueue addOperation:self.downloadOP]; //Here's the error
}
}
When I add a breakpoint just before the error-line, both self.downloadQueue and self.downloadOP are retained correctly (not nil).
The strange this is: in this very class I have a second NSOperationQueue with other NSOperations that are declared and treated in the same way as downloadQueue and downloadOP. And they work perfectly.
And yes, GTMDownloadOperation is a child-class of NSOperation and has a -(void)main method.
I don't know what to do now. If you don't have any idea about the reason of that error, how can I analyze the situation more accurately? (Product > Analyze doesn't complain about potential leak at that position).
Thanks for your help.
Oh man...
That took a while, but finally I know that the problem was in the for-loop.
The statement
self.downloadOP = [[[GTMDownloadOperation alloc]initWithImage:tmpImg]autorelease];
was accessing the variable downloadOP again and again in every iteration. Using the same NSOperation seemed to crash its retainCount.
I changed it to
GTMDownloadOperation *downloadOP = [[GTMDownloadOperation alloc]initWithImage:tmpImg];
and it works without error. Silly me.
you're not calling [super init] inside your constructor?
Assuming you're subclassing NSOperation (or NSObject etc...), you probably should!
why do you realloc and init your queue?
couldn't it be just one for your singleton class?
and...
[self.downloadQueue setMaxConcurrentOperationCount:2];
self.downloadQueue = [[[NSOperationQueue alloc]init]autorelease];
the first line is executed on an old queue, then you create a new one that have no limits
when do you call the second line (alloc a new queue) you release the old one (if any)
try this:
if (!downloadQueue){
self.downloadQueue = [[[NSOperationQueue alloc]init]autorelease];
}
[self.downloadQueue setMaxConcurrentOperationCount:2];
and remember to add:
self.downloadQueue = nil;
in your dealloc method (even if it's a singleton, and it won't be called while your app is running)
I believe the problem is in the implementation of your operation. I suggest two courses: try creating some simple block based operations that just log hello world and add them to the queue. They will most likely wok, letting you know the queue is functional. Then start adding log messages to you subclass to see which methods get called and finish properly.
This should lead you to the problem.

iPhone - Will this leak?

I have a setter like this:
- (UIImagePickerController *) foto {
if (_foto == nil) {
_foto = [[UIImagePickerController alloc] init];
_foto.delegate = self;
}
return _foto;
}
it is declared like
#property (nonatomic, retain) UIImagePickerController *foto;
with
#synthesize foto = _foto;
on my dealloc I have
[_foto release];
At some point in my code I want to do this
self.foto = nil;
but something in my soul says the object assigned to self.foto previously will leak, because it was alloc on the setter... how do I make it right?
thanks.
Edit: No, that should be fine. As long as you don't assign something else to _foto before you release, it should work.
Yup. You create an object, then loose the pointer to it. If you throw an autorelease on the init line, that will fix it. You could also use ARC.
The init line doesn't actually do anything... You assign the pointer to an object you create, then assign it to something else.
I don't think there is a leak there. When you assign to self.foto like this:self.foto = nil;, it will release the former one automatically. If you assign it by this way: _foto = nil;, you need to release it manually before the assignment.
Yes that works, and will not leak. When you set the value of _foto, its retain count is 1 (because you called alloc). As long as you release it (which you've said you do) in dealloc, you should be fine, as the retain count will go back to 0. UNLESS your setter is ALSO written by you, and written improperly. It needs to explicitly release the old value, if it's not nil. Something like this:
- (void)setFoto:(UIImagePickerController*)foto {
if (_foto) {
[_foto release];
_foto = nil;
}
if (foto)
_foto = [foto retain];
}

Pulling an NSArray out of a NSMutableArray

I have an NSMutableArray which is storing a list of other arrays. And when i run the code.
NSLog(#"%#",[[appDelegate teamRoster]objectAtIndex:[indexPath.row]class])
It returns and tells me that i am looking at an Array,
however when i try to do the following
[selectedRowerView tempArray] = [[appDelegate teamRoster]objectAtIndex:[indexPath.row]];
The program errors out. Anyone have any ideas why this might be happening?
You have to understand that [selectedRowerView tempArray] is actually a command / message that is being sent. In C++ equivalent, you are calling selectedRowerView->tempArray() = .... Which doesn't make logical sense because you cannot make an assignment to a function.
What you're trying to do is set the tempArray. If you have the proper setters/getters set-up, you can just run: selectedRowerView.tempArray = ...;
Just make sure that tempArray has a #property and is #synthesize'd.
How about this?
selectedRowerView.tempArray = [[appDelegate teamRoster]objectAtIndex:[indexPath.row]];
…assuming that tempArray is a synthesized property à la
#property (nonatomic, readwrite, retain) NSArray *tempArray;
#synthesize tempArray;
Clarification:
selectedRowerView.tempArray = …;
gets internally processed to
[selectedRowerView setTempArray:…];
which is a setter method.
While
selectedRowerView.tempArray;
gets internally processed to
[selectedRowerView tempArray];
which is a getter method.
Subtle but important difference.
The meaning of foo.bar depends on the very context (enclosing expression) it is used in.

Filling an NSMutableArray with a Set of Classes and Then Getting them Back

Hopefully I can make this clear, but I am new to Objective-C and to be honest not great with Arrays in the first place.
So, I have a Singleton class (called SingletonState) that I am using to pass variables around my app (please can we leave the whether I should use Singleton classes out of this - I will fix that later). In this class, I have an NSMutableArray (called arrayMyEvents). I have also created a class that I am going to store a list of events (called EventClass). When the user logs in, I call a web service and get back 3 strings. The 3rd string is a comma separated list of value. I parse the data and populate the custom class EventClass. I then add this class to the SingletonState.arrayMyEvents.
I have all of this working. I can go to another ViewController and access the "count" of items in arrayMyEvents.
PROBLEM: I now want to edit one of the ScheduledEventsClass"es" in my array. How do I get access to it and edit some of the properties and update the one in my SingletonState class?
Here is some of the code, that I've tried:
NSString *sWebServiceEvents = [[NSString alloc] initWithFormat:#"%#", [result objectAtIndex:2]];
if ( [ sWebServiceEvents isEqualToString:#"NULL" ] != true ) {
NSArray *arrayEvents = [sWebServiceEvents componentsSeparatedByString:#","];
// If the array has not been initialized they initialize it.
if (sharedState.arrayMyEvents == nil) {
sharedState.arrayMyEvents = [[NSMutableArray alloc ] init ];
}
for (NSString * sEvent in arrayEvents) {
// Set equal to the value of the array (the Event Number) at the same
// position as the row that we are being asked to return a cell/row for.
EventClass *eventClass = [[EventClass alloc] retain];
eventClass.sEvent = sEvent;
[ sharedState.arrayEvents addObject:eventClass ];
}
NSLog(#"LoginView - sharedState.arrayMyEvents Count: %d", [sharedState.arrayMyEvents count]);
}
Here is me trying to access it in another ViewController:
EventClass *eventClass =
[sharedState.arrayMyEvents objectAtIndex:row ];
NSLog(#"eventClass.sEventNumber: ", eventClass.sEventNumber);
eventClass.sLocation = #"Jason's Big Location";
You're going to have some memory leaks from the sEvent loop. [[EventClass alloc]retain] leaves you an uninitialized EventClass object with a reference count of 2. You'll need to change that to [[[EventClass alloc] init] autorelease] to keep it from leaking. The arrayEvents NSMutableArray will retain it during the addObject: call. (Shouldn't that be [sharedState.arrayMyEvents addObject: eventClass] in the loop?)
After that, all you have to do to edit the EventClass object in the second block of code is edit it. The eventClass variable is a pointer to an object in the array. Anything done to that object doesn't affect the pointer referencing it, it affects data referenced by it. The code you have in the second block should change the sLocation of the selected object as you intend.
You have a few more memory leaks in there, too. Use Cmd-Shift-A to build with the static analyzer and it'll tell you where.
Maybe the problem is that you put them in sharedState.arrayEvents but try to take them out of sharedState.arrayMyEvents. Different variables.
Also, lots of memory leaks.
Thanks John and St3fan, your answers and time are appreciated!!!
I think that I figured out my issue:
Basically, the class that I created (EventClass) had the properties setup like this:
#property (nonatomic, assign) NSString *sStudyNumber;
#property (nonatomic, assign) NSString *sTheater;
but, they should be (or at least I got it to work like this):
#property (nonatomic, retain) NSString *sStudyNumber;
#property (nonatomic, retain) NSString *sTheater;
Then, in my second view I was able to do this:
EventClass *eventClass = [sharedState.arrayMyEvents objectAtIndex:row ];
NSLog(#"MyEvents: %#", eventClass.sEventNumber);
eventClass.sLocation = #"Jason's Big Location";
I then checked it in another method of the view using this and it was still there:
EventClass *eventClass = [sharedState.arrayMyEvents objectAtIndex:row ];
NSLog(#"MyEvents: %#", eventClass.sEventNumber);
NSLog(#"MyEvents: %#", eventClass.sLocation);
I also, checked it in yet another view and the value was maintained in the SharedState.arrayMyEvents without issue. :)
In the end, I believe that I boiled down to the difference between "assign" and "retain".
Now, on to the memory leaks :(
Please, let me know if you see any other issues with this.
Thanks,
Jason

Do I have a leak with this statement?

The statement is:
//Pass the copy onto the child controller
self.childController.theFoodFacilityCopy = [self.theFoodFacility copy];
My property is set to:
#property (nonatomic, retain) FoodFacility *theFoodFacilityCopy;
The reason I think I have a leak is because copy retains the value and then my dot syntax property also retains the value. Doubly retained.
What is the correct way of writing the above statement?
yes, you do have a leak there.
SomeClass *someObj = [self.theFoodFacility copy];
self.childController.theFoodFacilityCopy = someObj;
[someObj release];
This mirrors the recommended approach for initializing an object too:
SomeClass *someObj = [[SomeClass alloc] init];
self.someProperty = someObj;
[someObj release];
In both cases the first line returns an objects with a retain count of 1, and you treat it identically after that.
As mentioned by others, that is indeed a leak. If you expect to be using copies in this way, it’s likely your property should be declared copy instead and the synthesized accessor will do the work for you.
You are right. The cleanest way is something like
id temp = [self.theFoodFacitlity copy];
self.childController.theFoodFacilityCopy = temp;
[temp release]
You want to read the apple site on memory management a lot until these rules become second nature.
What is the advantage of doing this vs just setting the property to copy?
#property (nonatomic, copy) FoodFacility *theFoodFacilityCopy;