Selecting an object from a class method?

I'm just wondering if this is right or bad practice? (i.e. using the class method to place / initialize the instance)? Also, I am right in thinking that I should free the instance in main (), since this is the only place where I have access to the instance pointer?

// IMPLEMENTATION
+(id) newData {
    DataPoint *myNewData;
    myNewData = [[DataPoint alloc] init];
    return myNewData;
}

.

// MAIN
DataPoint *myData;
myData = [DataPoint newData];
... stuff
[myData release];

EDIT:

Also follows

myNewData = [[DataPoint alloc] init];

be (or it doesn't matter)

myNewData = [[self alloc] init];

EDIT_002:

Strange, when I add auto ads, I get ...

alt text

EDIT_003:

@Dave DeLong, one final question is what your saying is capable of:

+(id) dataPoint {
    return [[[self alloc] init] autorelease];
}

not (where would you release mostly)

+(id) new {
    return [[self alloc] init];
}

cheers gary

+3
source share
4 answers

+dataPoint. , , , ( ) , , "", +1. +0 () , , .

@Peter, , [ClassName className]. : [NSArray array], [NSData data], [NSString string] .. , [DataPoint dataPoint], return [[[self alloc] init] autorelease];

[self alloc] , . IE, MutableDataPoint, ( [self alloc]), [MutableDataPoint dataPoint] a MutableDataPoint, [DataPoint alloc], DataPoint ( , ). ( self , . , , . Class)

Edit:

, +1, ( ) +new (.. DataPoint * p = [DataPoint new];). +new, , , +alloc/-init... .

# 2 (Re: Edit_003):

(+dataPoint), , +new , -release. .

+14

:

+ (id)dataPoint {
    return [[[MyDataPoint alloc] init] autorelease];
}

: init; . , GC, .

+ dataPoint .

+5

newData - , API Cocoa (, [NSString ] [ NSData]).

, ( ) . , alloc, new, copy mutableCopy, / . ( newData " " ), , , .

[DataPoint alloc] vs. [self alloc], , . Java, [DataPoint alloc], (self, java this), ). , Objective-C, Objective-C Java , .

+2

EDIT_002:

, , ...

. , :

  • Objective-C +1 ( )

    newData. new .

  • -

    . .

  • ( , )

    A new (, newData) , , new . . , ...

  • , +0 ( )

    , . , . :

  • +0 [sic] , +1 ()

    , new, , . , , , , , .

, Cocoa . :

  • , .
  • , new, .

# 2, , , .

+1

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


All Articles