Objective-c Memory Question - objective-c

I have a question regarding memory management in objective-c. I have read Apple's various documents regarding this but I still don't seem to be grasping it. I have created a small sample app to demonstrate my confusion. When I launch the app Activity Monitor states that it's using about 7MB. When I execute the main loop the memory usage goes up to 44MB which is expected. However, when I release the array I only get about 14MB back in Activity Monitor. The app continues to use about 30MB. Shouldn't I get all my memory back return the "Real Memory" to 7MB in Activity Monitor?
What am I doing wrong?
Thanks in advance.
Here is the AppDelegate:
- (IBAction) buildArray:(id)sender {
values = [[NSMutableArray alloc] init]; // values is an instance variable of the appDelegate
for(int i = 0; i < 500000; ++i) {
NSString *tempString = [NSString stringWithFormat:#"New Object %i", i];
[values addObject:tempString];
}
[valuesTable reloadData]; // valuesTable is a NSTableView to diplay the array.
}
- (IBAction) clearMemory:(id)sender {
[values release];
[valuesTable reloadData];
}
- (int) numberOfRowsInTableView: (NSTableView *) tableView {
if (values) {
return [values count];
} else {
return 0;
}
}
- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row {
return [values objectAtIndex:row];
}

This has been answered a multitude of times before; but the act of releasing an object does not immediately return memory to the system. The application holds on to parts of the arena that lie unused, waiting for them to be reallocated.
If they are actually requested by the system, it gives up these resources, but as long as no other process wants the memory, your application will hang on to it, "just in case".

Related

Is a value inside an NSDictionary released when removed?

I have something along the line of this :
#implementation ImageLoader
NSMutableDictionary *_tasks;
- (void) loadImageWithURL:(NSURL *)url callback:(SMLoaderCallback)callback {
NSMutableArray *taskList = [_tasks objectForKey:urlString];
if (taskList == nil) {
taskList = [[NSMutableArray alloc] initWithCapacity:5];
[taskList addObject:callback];
[_tasks setObject:taskList forKey:urlString];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [[UIImage alloc] initWithData:data];
for (SMLoaderCallback cb in taskList) {
cb(image, nil);
}
[_tasks removeObjectForKey:url.absoluteString];
});
});
} else {
[taskList addObject:callback];
}
}
#end
In here, I'm trying to queue up image downloads to gain performance (as an exercise only). So I'm keeping a NSDictionary that maps an URL with an array of callbacks to be called whenever the data is downloaded.
Once the image is downloaded, I no longer need this array, so I remove it from the dictionary.
I would like to know if, in this code (with ARC enabled), my array along with the callbacks are correctly released when I call [_tasks removeObjectForKey:url.absoluteString].
If your project uses ARC and that dictionary is the only thing that is referencing to those values, yes. it will be remove permanently.
ARC keeps track of number of objects that is pointing to some other object and it will remove it as soon as the count reaches 0.
so adding to dictionary -> reference count += 1
removing from dictionary -> reference count -= 1
Somewhe

Can't Add Object to NSMutableArray

I have a class called KCBlackjack. The class contains this code:
playerHand = [[NSMutableArray alloc] init];
dealerHand = [[NSMutableArray alloc] init];
blackjack = [[KCBlackjack alloc] initWithNumberOfDecks:6];
[self deal];
[blackjack dealTo:playerHand dealer:dealerHand];
- (void)dealTo:(NSMutableArray *)player dealer:(NSMutableArray *)dealer {
// How many cards are left
NSLog(#"Cards in Deck: %d", [_decks count]);
// Deal to player then dealer
for (int i = 0; i <= 1; i++) {
[player addObject:[_decks lastObject]];
[_decks removeLastObject];
NSLog(#"%#", player);
if(_delegate && [_delegate respondsToSelector:#selector(didDistributeCard:withValue:)]) {
KCCard *aCard = (KCCard *)[player objectAtIndex:player.count-1];
[_delegate didDistributeCard:aCard to:player withValue:[aCard value]];
}
[dealer addObject:[_decks lastObject]];
[_decks removeLastObject];
NSLog(#"%#", dealer);
if(_delegate && [_delegate respondsToSelector:#selector(didDistributeCard:withValue:)]) {
KCCard *aCard = (KCCard *)[dealer objectAtIndex:dealer.count-1];
[_delegate didDistributeCard:aCard to:dealer withValue:[aCard value]];
}
}
NSLog(#"Done Dealing");
NSLog(#"Cards Remaining in Deck: %d", [_decks count]);
NSLog(#"Player: %#\n\n", player);
NSLog(#"Dealer: %#\n\n", dealer);
}
Inside of my game controller, I set player to my player array as well as the dealer his. When this is run however, it doesn't work. No objects are added to the player array that player or dealer is assigned.
When the code is in the game controller, it works, but not in this class. I figure something is not initializing, but in the game controller, the player and dealer are both initialized.
If you think of it from a OO perspective, dealer and player are really objects that should receive a message such as addCardToHand:(Card )aCard. The way you are doing it, Lucas has exactly right, you get a copy of his array which is not mutable. I'd much rather see some dot notation such as player.hand addCard:(Card)aCard if you don't want the player to handle the card himself (watch for card sharps! :-) ).
I think if you refactor with objects you can have clean code that works, and probably get rid of that delegation stuff (which is a bit confusing just reading).
Good luck - blackjack is fun!
Damien

Generating images in the background

I am currently building an application that generates images and stores them in an NSMutableArray, which then used in a UINavigation (Cell.imageView.image). I need to be able to handle up to 2000 images without causing lag in my application.
Currently how I set this generating is by calling the generating method when cellForRowAtIndexPath is accessed. Which seems to cause a 4-5 second lag before the next navigation is called.
fortunately after those 4-5 seconds the generating is done and there is no issues.
In the world of iProducts waiting 4-5 seconds isn't really an option. I am wondering what my options are for generating these images in the background. I tried using threads [self performSelectorInBackground:#selector(presetSnapshots) withObject:nil];
but that only gave me issues about vectors for some reason.
Heres the generating code:
-(void)presetSnapshots{
//NSAutoreleasePool* autoReleasePool = [[NSAutoreleasePool alloc] init];
for (int i = 0; i < [selectedPresets count]; ++i){
GraphInfo* graphInfo = [selectedPresets objectAtIndex:i];
graphInfo.snapshot = [avc takePictureOfGraphInfo:graphInfo PreserveCurrentGraph:false];
[graphInfo.snapshot retain];
}
//[autoReleasePool drain];
presetSnapshotFinished = YES;
}
inside - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { is
if (presetSnapshotFinished == NO){
[self presetSnapshots];
//[self performSelectorInBackground:#selector(presetSnapshots) withObject:nil];
}
cell.imageView.image = [[selectedPresets objectAtIndex:indexPath.row] snapshot];
Edit:
I also rather not use coreData for this. The images are 23x23 and coming out to about 7kb. So its about 6MB being use at any giving time in memory.
You can use Grand Central Dispatch (GCD) to fire up [self presetSnapshots]
dispatch_queue_t working_queue = dispatch_queue_create("com.yourcompany.image_processing", NULL);
dispatch_queue_t high = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,NULL);
dispatch_set_target_queue(working_queue,high);
dispatch_queue_t main_queue = dispatch_get_main_queue();
dispatch_async(working_queue,^{
if (presetSnapshotFinished == NO){
[self presetSnapshots];
}
dispatch_async(main_queue,^{
cell.imageView.image = [[selectedPresets objectAtIndex:indexPath.row] snapshot];
});
});

Basic IOS OOP - structure and implementation

I am creating a basic guessing game in iOS for my kids, and I think there are some fundamental gaps in my understanding of how I should be creating and releasing objects throughout the lifecycle of the app. I have been reading up on retain and release cycles but I think my issue is more to do with the fundamental architecture of the app and how I may be poorly trying to instantiate and then kill a few key objects of the app.
The problem centers around two specific classes.
I have a game class, which I have designed to hold all the information that the game requires to run. When it is init-ed, it holds all instance variables that point to arrays that hold strings such as the various clues, etc. It's basically a container for all the data that the game requires.
I have a game view controller, that creates and an instance of the game class and queries it so as to present on screen the various elements contained with the game object.
This works perfectly the fine. When the user starts a new game, a new instance of the game class is allocated and init-ed and away they go.
The issue comes in when I come to generate a new game. This happens a number of ways. Either The user finishes the game and starts another one or the user quits the current game and then starts a new one.
In my thinking, I would just release the game object and alloc and init a new one. However, I notice running on the device and looking through the profiler, that the game object isn't released at all.It's still, there and each instantiation of the game creates a new game object with the old one still sitting there with no pointers to it.
Fiddling around with the code, I noticed that I did not implement a dealloc method in the Game class...but when I try to do that, the app crashes, I suspect because I am trying to release a previously released object.
Ideally what I am trying to do is get rid of the old Game object, or replace the old one (overwrite) with a new one each time a new game is started.
However, is this approach wrong? Should I be doing it a completely different way? Such as only ever creating a single instance of the game class and rewriting a method inside that class so as to generate a new set of clues, etc everytime a new game starts and the GameViewController tells it to?
Is there a 'best practice' way to do this?
So you've got an idea of what I am doing, code is below for the GameViewController, where an instance of the Game class is created:
#import "GameViewController.h"
#implementation GameViewController
#synthesize game = _game;
-(void)startNewGameOfLevel:(NSInteger)level
{
if(!_game)
{
Game *g = [[Game alloc]initGamewithLevel:level];
[self setGame:g];
[g release]; g = nil;
}
[self set_currentlevel:[_game _currentLevel]];
// set up popover to show the rounds goal letter
[self setUpPopOver];
}
-(void)quitTheCurrentGameAndStartNewGame
{
[_game release]; _game = nil;
[self clearGamePlayingField];
animationStepIndex = 0;
[self startNewGameOfLevel: _currentlevel];
}
Game class (abridged) with the designated initializer of the Game class:
#import "Game.h"
#implementation Game
#synthesize arrayOfLowerCaseLetters = _arrayOfLowerCaseLetters;
#synthesize arrayOfPhrases= _arrayOfPhrases;
#synthesize goalLetter = _goalLetter;
#synthesize goalPhrase = _goalPhrase;
#synthesize gameLetterPool = _gameLetterPool;
#synthesize _indexForGoalLetter, _numberOfLevelsInGame, _currentLevel, _numberOfWhackHoles, _numberOfLettersInGameLetterPool;
-(id)initGamewithLevel:(NSInteger)level
{
[super init];
//create an array of lower case letters. These will
//contain the full alphabet of all possible letters
NSArray *arrayOfLCLetters = [[NSArray alloc] initWithObjects:#"a", #"b", #"c", #"d",#"e", #"f", #"g", #"h", #"i", #"j", #"k", #"l", #"m", #"n", #"o", #"p", #"qu", #"r", #"s", #"t", #"u", #"v", #"w", #"x",#"y", #"z",#"ch", #"sh", #"th", nil];
[self setArrayOfLowerCaseLetters: arrayOfLCLetters];
[arrayOfLCLetters release];arrayOfLCLetters = nil;
//create an array of phrases.
// These must correspond with each of the letters. e.g. a = apple.
NSArray *phrases= [[NSArray alloc ] initWithObjects:
#"apple",
#"butterfly",
#"cat",
#"dog",
#"egg",
#"frog",
#"ghost",
#"horse",
#"igloo",
#"jam",
#"kite",
#"leaf",
#"moon",
#"nut",
#"orange",
#"pig",
#"queen",
#"rabbit",
#"snake",
#"tree",
#"umbrella",
#"van",
#"water",
#"x-ray",
#"yak",
#"Zebra",
#"chair",
#"shoes",
#"thumb",
nil];
[self setArrayOfPhrases:phrases];
[phrases release]; phrases = nil;
//choose a random number to be the index reference for
// each goal letter and goal phrase.
[self set_indexForGoalLetter:(arc4random()%[_arrayOfLowerCaseLetters count])];
NSLog(#"index for goal letter is:, %i", _indexForGoalLetter);
//set Goal letter and goal phrase
[self setGoalLetter: [_arrayOfLowerCaseLetters objectAtIndex: _indexForGoalLetter]];
[self setGoalPhrase: [_arrayOfPhrases objectAtIndex:_indexForGoalLetter ]];
//set current level
[self set_currentLevel: level];
//[self set_currentLevel: 2];
//set number of whackholes by level
[self set_numberOfWhackHoles: [self numberOfWhackHolesByLevel:_currentLevel]];
//generate size of Letter pool by level
[self set_numberOfLettersInGameLetterPool:[self numberOfLettersInLetterPoolbyLevel:_currentLevel]];
////////////////////////////
/// Game letter pool
///////////////////////////
//set up array ton hold the pool of letters
NSMutableArray *gp = [[NSMutableArray alloc] initWithCapacity:_numberOfLettersInGameLetterPool];
[self setGameLetterPool: gp];
[gp release];gp = nil;
//add the goal letter to this pool
[_gameLetterPool addObject:_goalLetter];
int i = 1;
while (i < _numberOfLettersInGameLetterPool) {
NSString *letter = [_arrayOfLowerCaseLetters objectAtIndex:(arc4random()%[_arrayOfLowerCaseLetters count])];
if ([_gameLetterPool containsObject:letter] == false)
{
[_gameLetterPool addObject:letter];
i++;
}
}
NSLog(#"********** Game created ***************");
NSLog(#"pool of letters is: %#", [_gameLetterPool description]);
NSLog(#"****************************************");
NSLog(#"current goal letter is: %#", _goalLetter);
NSLog(#"****************************************");
NSLog(#"current goal phrase is: %#", _goalPhrase);
NSLog(#"****************************************");
return self;
}
-(void)dealloc
{
[super dealloc];
[_arrayOfLowerCaseLetters release]; _arrayOfLowerCaseLetters = nil;
[_arrayOfPhrases release]; _arrayOfPhrases = nil;
[_goalLetter release];_goalLetter = nil;
[_goalPhrase release]; _goalPhrase = nil;
[_gameLetterPool release];_gameLetterPool = nil;
}
The number one problem is that [super dealloc] must be the absolute last thing you do in -dealloc. This is because it is the dealloc method in NSObject that actually frees the memory, so by the time you get back to it, your instance variable pointers may already be garbage.
Other issues:
In init, do self = [super init]; The super object is allowed to return a different self pointer on init.
startNewGameOfLevel: and quitTheCurrentGameAndStartNewGame should use the property, not the bare instance variable.
-(void)startNewGameOfLevel:(NSInteger)level
{
if(![self game])
{
Game *g = [[Game alloc]initGamewithLevel:level];
[self setGame:g];
[g release]; g = nil;// g = nil, not necessary when it's about to go out of scope
}
[self set_currentlevel:[[self game] _currentLevel]]; // don't use _ to start methods - Apple reserves this convention
// set up popover to show the rounds goal letter
[self setUpPopOver];
}
-(void)quitTheCurrentGameAndStartNewGame
{
[self setGame: nil];
[self clearGamePlayingField];
animationStepIndex = 0;
[self startNewGameOfLevel: _currentlevel];
}
There are probably other issues in the body of your code - make sure you build with static analysis enables - it will catch many of them.

iOS Singleton Variables Not Keeping Their Values

So I'm still kind of new to Objective-C, and this was my first app that I'm now updating. The idea is this: The whole app is basically various lists of stuff. It asks the API for 15 posts, shows those with a Load More button. Click Load More, it loads 15 more, etc. The API that it loads these from has a token system with a timeout built in. Too long between requests, and you have to get a new token. So I want to have a singleton to use anywhere in my app so I can just do [APIMachine getToken] and behind the scenes, it checks if the time since the last request was too long (or this is the first request), if so, gets a new token, otherwise returns the one we already have. I'm following the singleton pattern I've found in so many places, but every time the Load More button uses [APIMachine getToken]it gets either nothing or something completely random. I had it print this stuff in the logs, and one time I even got a UITableViewCell as my token. Looks like variables are being overwritten somehow. But I really can't figure it out.
So here it is:
static PoorAPI2 *_instance;
#implementation PoorAPI2
#synthesize apiToken, timeOpened, tokenTTL;
+ (PoorAPI2*)sharedAPI
{
#synchronized(self) {
if (_instance == nil) {
_instance = [[super allocWithZone:NULL] init];
}
}
return _instance;
}
-(NSString *)API_open{
//boring code to get api token redacted
if ([doneness isEqualToString:#"success"]) {
NSDictionary *data = [json objectForKey:#"data"];
apiToken = [data objectForKey:#"api_token"];
tokenTTL = [data objectForKey:#"ttl"];
timeOpened = [NSDate date];
}else{
NSLog(#"FFFFFFFUUUUUUUUUUUU this error should be handled better.");
}
return apiToken;
}
-(BOOL)isConnectionOpen{
return ([timeOpened timeIntervalSinceNow] > tokenTTL);
}
-(NSString *)getToken{
if([self isConnectionOpen]){
return apiToken;
}else{
return [_instance API_open];
}
}
-(id)init{
if(self = [super init]){
apiToken = [[NSString alloc] initWithString:#""];
timeOpened = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
tokenTTL = 0;
}
return self;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedAPI]retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
#end
I can only hope I'm doing something seriously foolish and this will be a hilarious point-and-laugh-at-that-guy thread. Then at least my app will work.
In API_open, you store three objects in instance variables, but they're not objects you own, so they'll probably be gone by the time you need them and replaced by something unpredictable. You need to retain them or use proper setters.
You problem is:
static PoorAPI2 *_instance;
C, and by inheritance Objective-C, do not initialize variables. Just change to:
static PoorAPI2 *_instance = nil;
Also I am of the school that adding extra code to try to prevent the singleton from being used as a single is a total waste of time, and only give you more code with more possibilities for bugs.
So if I was you then I would remove every method from +[PoorApi2 allocWithZone:] and down. Objective-C is a dynamic language and if a client wanted to instantiate a second instance of your singleton then it would be able to do so despite all your wasted extra lines of code. At the most I would add a log like this:
-(id)init{
if (_instance) NSLog(#"WARNING: PoorAPI2 already has a shared instance.");
if(self = [super init]){
apiToken = [[NSString alloc] initWithString:#""];
timeOpened = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
tokenTTL = 0;
}
return self;
}
Creating a second instance of a singleton is a programming error and should be caught in development. Not a problem you should add extra lines of code to hide.