I am getting the leak in the following code - iphone

I am getting the leaks as 100%. I don't know how to release the object after it returns
Could you explain the procedure how to release the allocated Titles object.
-(Titles *)listTiles
{
Tiles* tile = [[Tiles alloc] init];
tile.googleTile_X = (int)tileX;
tile.googleTile_Y = (int) pow(2, aZoom) - 1- tileY ;
tile.zoomLevel = aZoom;
return tile;
}

You're sending -alloc, and failing to send -release or -autorelease to the object you've created.
Read Apple's introductory documentation on memory management.

In general it depends, but in that particular case I believe you can use return [tile autorelease].
P.S.: Please format your code correctly.

-(Titles *)listTiles
{
Tiles* tile = [[[Tiles alloc] init] autorelease];
tile.googleTile_X = (int)tileX;
tile.googleTile_Y = (int) pow(2, aZoom) - 1- tileY ;
tile.zoomLevel = aZoom;
return tile;
}

Related

How to call a method using a shared instance?

I have a method which calculates loan payments based on car price, interest rate and number of years, this method is in my model and is accessed through my main view controller.
I created a singleton in the model but since I created it the method that calculates the payments stopped working for some reason. I have made sure that I have created the shared instance, It was working before I implemented the singleton.
Any help would be appreciated. I have not received any errors.
Here is the singleton I created.
+(id) sharedCalculatorBrain
{
static id sharedCalculatorBrain = nil;
if (sharedCalculatorBrain == nil)
{
sharedCalculatorBrain = [[sharedCalculatorBrain alloc]init];
}
return sharedCalculatorBrain;
}
Here is how I have created the object.
CalculatorBrain * brain = [CalculatorBrain sharedCalculatorBrain];
and I call the method by using:
[brain calculatePaymentPlan:[self.txtLoanAmount.text doubleValue] :[self.txtInterestRate.text doubleValue] :[self.txtNumberOfYears.text doubleValue]];
Not sure if it is a typo, but check your code if you allocate the singleton instance using:
sharedCalculatorBrain = [[sharedCalculatorBrain alloc] init];
Because if this is the case, you need to do:
sharedCalculatorBrain = [[CalculatorBrain alloc]init];
Hope this helps, good luck with your project!

ABUnknownPersonViewController crashes

Im using this code to show an ABUnknowPersonViewController for showing a record from a person which was created from a vCard String:
- (ABRecordRef)person {
if (person == NULL) {
ABPersonCreator *creator = [[ABPersonCreator alloc] initWithVcardString:vcardString];
person = creator.person;
CFRetain(person);
[creator release];
}
return person;
}
- (UIView *)fullscreenView {
unknownPersonController = [[ABUnknownPersonViewController alloc] init];
unknownPersonController.displayedPerson = self.person;
unknownPersonController.allowsAddingToAddressBook = YES;
unknownPersonController.allowsActions = YES;
unknownPersonController.unknownPersonViewDelegate = self;
return unknownPersonController.view;
}
Can someone help me out with this?
thx Philip
The solution to this problem for me was that I wasn't passing the right stuff when building the ABRecordRef. For instance, I tried to simply set a string to a property when it instead wanted a kABMultiStringPropertyType. The exception would only occur after trying to launch the UnknownPersonViewController.
Check your datatypes and make sure that you're building the right thing.
Shouldn't have unknownPersonViewController have an autorelease, as it's view's returned?

singleton class memory leakage

I set up a singleton following the instructions at this tutorial, but when I analyze it I see the following memory leaks:
How do I rectify this memory leakage in my singleton class?
I think that whoever that wrote that tutorial didn't write this right:
[[self alloc] init];
Instead, it sould be:
_sharedMySingleton = [[MySingleton alloc]init];
I hope it helps
You do not assign the allocation to a variable. Change it to this:
+(MySingleton*)sharedMySingleton
{
#synchronized(self)
{
if (!_sharedMySingleton)
_sharedMySingleton = [[self alloc] init];
}
return _sharedMySingleton;
}
EDIT my typing was too slow, others have already replied :)
It looks like when you return _sharedMySingleton, it will still be nil. And hence allocated the next time, too. You should try setting it when the alloc is done.
[[self alloc] init]; - is not assigned to the object

EXC_BAD_ACCESS in iPhone app - memory management issue

For reference, I've already read:
memory management question -- releasing an object which has to be returned
iPhone: Return NSMutableArray in method while still releasing
Releasing objects returned by method
Which I thought would help :).
This app is a teaching tool and is intended to help people visualize simple genetics. Just some background so the variable names and stuff will make sense. Here's the main code that executes when the app runs:
- (void)viewDidAppear:(BOOL)animated {
ThingzCore *core = [[ThingzCore alloc] init];
ThingzThing *thing1 = [[ThingzThing alloc] init];
thing1.breed = #"AB";
thing1.pattern = #"AC";
thing1.color = #"CA";
thing1.gender = #"XY";
thing1.generation = 1;
thing1.isEgg = NO;
ThingzThing *thing2 = [[ThingzThing alloc] init];
thing2.breed = #"CD";
thing2.pattern = #"BA";
thing2.color = #"CB";
thing2.gender = #"XX";
thing2.generation = 1;
thing2.isEgg = NO;
NSLog(#"Breeding GD BR PT CL G");
ThingzThing *child = [core mateFather:thing1 withMother:thing2];
NSLog(#"Round 1: %# %# %# %# %d",child.gender,child.breed,child.pattern,child.color,child.generation);
sleep(10);
child = [core mateFather:thing1 withMother:thing2];
NSLog(#"Round 2: %# %# %# %# %d",child.gender,child.breed,child.pattern,child.color,child.generation);
sleep(10);
child = [core mateFather:thing1 withMother:thing2];
NSLog(#"Round 3: %# %# %# %# %d",child.gender,child.breed,child.pattern,child.color,child.generation);
sleep(10);
child = [core mateFather:thing1 withMother:thing2];
NSLog(#"Round 4: %# %# %# %# %d",child.gender,child.breed,child.pattern,child.color,child.generation);
sleep(10);
[thing1 release];
[thing2 release];
[core release];
}
And here's what happens when I run it in various ways:
Running without breakpoints, it crashes, with no console message, after the 2nd sleep() but before the "Round 3" NSLog.
Running with breakpoints enabled, but none defined, it runs through the entire sequence. After the fourth sleep(), it crashes with EXC_BAD_ACCESS.
Running with breakpoints enabled and NSZombiesEnabled, it does the same thing as above - no further information, just EXC_BAD_ACCESS.
Running in Instruments, no leaks are shown.
This is the routine being called four times:
-(ThingzThing *)mateFather:(ThingzThing *)father
withMother:(ThingzThing *)mother {
// will we be doing a mutation?
int mutationPercentage = father.generation + mother.generation;
int mutationNumber = (arc4random() % ((unsigned)100 + 1));
BOOL isMutation = NO;
if (mutationNumber <= mutationPercentage) {
isMutation = YES;
}
// get possibilities
NSArray *possibilities = [self possibilitiesByMatingFather:father
withMother:mother
mutations:isMutation];
// randomly select one of the possibilities
int keeping = (arc4random() % ((unsigned)[possibilities count]));
return [possibilities objectAtIndex:keeping];
}
Without pasting in the ENTIRE code, the possibilitiesByMatingFather:withMother:mutations function is returning an NSMutableArray. That routine declares the array by using:
NSMutableArray *possibilities = [NSMutableArray array];
It then:
return possibilities;
It does not send a release or autorelease message to possibilities; my understanding is that creating the array the way I have is an implicit autorelease. I didn't want to alloc the array, because I'm returning it, so wouldn't have the opportunity to explicitly release it.
The objects held in the possibilities NSMutableArray are of a custom class. They are added as follows:
ThingzThing *newThing = [[ThingzThing alloc] init];
newThing.breed = choiceBreed;
newThing.gender = choiceGender;
newThing.color = choiceColor;
newThing.pattern = choicePattern;
newThing.generation = mother.generation + father.generation;
newThing.name = #"";
newThing.isEgg = YES;
[possibilities addObject:newThing];
[newThing release];
Which seems to work most of the time. At least, when breakpoints are enabled, the program runs through the code without complaint until the end, as noted above.
Any suggestions on what I'm doing wrong, here? It's obviously memory management issues of some kind, but I can't sort it in my head.
BTW, in a vain, throwing-things-at-the-wall attempt to figure it out, I did modify the one line from the main routine as follows:
// get possibilities
NSArray *possibilities = [[self possibilitiesByMatingFather:father
withMother:mother
mutations:isMutation] retain];
To no avail. Same results. So the problem isn't in retaining the array returned by possibilitiesByMatingFather:withMother:mutations. Forcing a retain on that return isn't helping.
Frequently in this type of situation, the actual error is not at the location shown in the debugger when the app halts.
For example, the debugger may be pointing to a method call, but the problem actually occurs inside the method -- not when the method is called.
To track things down, I would suggest setting a breakpoint just before the method call that triggers the error -- in your case, this would be the mateFather: withMother: call. Then step into that method. There is a good chance you will find that the problem happens inside that method -- or even inside a method called from within that method.
Check you have the correct property declarations of the string properties of class ThingzThing.
e.g.
#property (nonatomic, retain) NSString* breed;
NEED to be retain or copy NOT assign...
Found it. Buried eight method calls down, I was sending release to an NSArray that was obviously autoreleasing. When the initial calling routine (viewDidAppear) fell down into autorelease mode, it tried to autorelease the already-released object, and exploded. Good grief - is there any way XCode could have helped me track that down?
In any event, in case anyone runs across this, make bloody sure you're not sending a release message to something that you didn't explicitly alloc yourself. If you didn't alloc it, odds are it was autoreleasing itself, and you sending a release to it takes the retain count negative, and the Foundation framework vomits with an EXC_BAD_ACCESS.

Pointers, NSMutableArray, Retain, Loops and Confusion

It might be that the problem is straight forward but I don't get my head around it.
I have the following iPhone code
for(int x = 0 ; x < [allFriends count] ; x++)
{
Friend *f = [[Friend alloc] init];
f = [allFriends objectAtIndex:x];
if([uid isEqualToString:[f uid]])
{
[f AddAlbum:album];
[allFriends replaceObjectAtIndex:x withObject:f];
}
}
It doesn't matter where I call [f release] the app always crashes. Why? (BTW the loop runs a few thousand times)
Is there a more efficient way to do it?
I think I provided enough code, let me know if not!
Thanks heaps for your help!
The object you create in this line (and are presumably trying to release):
Friend *f = [[Friend alloc] init];
is immediately leaked when you then assign f to the object you get out of your array:
f = [allFriends objectAtIndex:x];
So it's really that object you're releasing, meaning that the pointer in the array is no longer valid (it's pointing at a released instance).
I think your code has some serious problems:
Why are you allocating a new Friend if you're going to immediately leak it?
Why replace an object in an array with the same object?
I think you can replace your code with this loop:
for (Friend *f in allFriends)
{
if([uid isEqualToString:[f uid]])
{
[f AddAlbum:album];
}
}
Seems like you're doing way more work than you need. Something like this (I think) does the same thing, but without the leaks or crashes:
for (Friend* f in allFriends) {
if ([uid isEqualToString:[f uid]]) {
[f addAlbum:album];
}
}