Why does this program take up so much memory?

I am learning Objective-C. I am trying to free all the memory that I use. So, I wrote a program to check if I am doing this correctly:

#import <Foundation/Foundation.h>

#define DEFAULT_NAME @"Unknown"

@interface Person : NSObject
{
  NSString *name;
}
@property (copy) NSString * name;
@end

@implementation Person
@synthesize name;
- (void) dealloc {
  [name release];
  [super dealloc];
}
- (id) init {
  if (self = [super init]) {
    name = DEFAULT_NAME;
  }
  return self;
}
@end


int main (int argc, const char * argv[]) {
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  Person *person = [[Person alloc] init];
  NSString *str;
  int i;

  for (i = 0; i < 1e9; i++) {
    str = [NSString stringWithCString: "Name" encoding: NSUTF8StringEncoding];
    person.name = str;
    [str release];
  }

  [person release];
  [pool drain];
  return 0;
}

I use a mac with a snow leopard. To check how much memory is being used, I open Activity Monitor at the same time as it starts. After a couple of seconds, it uses gigabytes of memory. What can I do to prevent it from being used so much?

+3
source share
1 answer

Firstly, your loop is incorrect. +stringWithCString:…is not +alloc/ +new…/ -copyso you do not have -releaseit.

Is one of them true:

  1. Not -release:

    str = [NSString stringWithCString: "Name" encoding: NSUTF8StringEncoding];
    person.name = str;
    
  2. Use -init:

    str = [[NSString alloc] initWithCString: "Name" encoding: NSUTF8StringEncoding];
    person.name = str;
    [str release];
    

, -[Person init]:

- (id) init {
  if ((self = [super init])) {
    name = [DEFAULT_NAME copy]; // <----
  }
  return self;
}

, №1, , , №2 , .

,

str = [NSString stringWithCString: "Name" encoding: NSUTF8StringEncoding];

str = [[[NSString alloc] initWithCString:......] autorelease];

an -autorelease d " NSAutoreleasePool ".

? , . *, . 10 9 .

№ 2 , . ( , - .)


:

*: A run loop - , . CLI, .

+5

Source: https://habr.com/ru/post/1748679/


All Articles