Goal C, when to use alloc and when not

I am trying to learn objective C, and one of the things that I find very strange is when to use alloc and when it is not. Take for example this piece of code:

NSURL *url =[NSURL URLWithString:@"http://www.apple.com"];

Why don't you need to do something like this to highlight it first?

UIAlert *alert = [[UIAlertView alloc]]

I'm sure there are only a few basic things in the C lens, but oddly enough, it's hard for me to find an explanation without posting. Thank!!

+5
source share
2 answers

+alloc , , -release -autorelease . , API . +URLWithString: , :

+ (id)URLWithString: (NSString *)str {
    return [[[self alloc] initWithString: str] autorelease];
}

+alloc , -autorelease.

Objective-C : . . , . +; -.

+alloc - . - . , , - :

+ (id)alloc {
    id result = malloc(class_getInstanceSize(self));
    if (result) {
        memset(result, 0, class_getInstanceSize(self));
        result->isa = self;
        result->retainCount = 1;
    }
    return result;
}

( , .) , +alloc NSObject, . Cocoa , +alloc, -init, -retain, -release .. Objective-C, , .

+alloc, . .

+6

alloc , .

NSURL *url =[[NSURL allo]initWithString:@"http://www.apple.com"], . , ,

NSLog ("Url path is %@",url);

(url)

[url release];

Objective C

,

NSURL *url =[NSURL URLWithString:@"http://www.apple.com"];

, url , , , ( )

+2

All Articles