Per la maggior parte delle operazioni, non utilizzare ->
a meno che non si stia scrivendo codice C o C++ con Objective-C. È più semplice per te, il compilatore e la gestione della memoria se crei le proprietà e le fai riferimento in modo appropriato.
@interface MYObject : NSObject {
@public // don't use this, please!
MYOtherObject *obj;
}
@property (retain) MYOtherObject *obj;
@end
@implementation MYObject
@synthesize obj;
@end
// later in your code
MYObject *thing = [[MYObject alloc] init];
MYOtherObject *other;
// Good
other = [thing obj];
other = thing.obj;
other = [thing valueForKey:@"obj"]; // I hope my KVC is correct here. :(
// Bad, and soon to be deprecated I believe. (all members are @protected unless you use @public)
other = thing->obj;
Perché è brutto? È possibile dichiarare i membri nel file di implementazione in questo modo: (a 64 bit e iPhone)
@interface MYObject : NSObject
@property (retain) MYOtherObject *obj;
@end
@implementation MYObject
@synthesize obj = _obj;
@end
Qui, chiamando thing->obj
produrrà nulla, ma gli errori dal momento che il membro è allocata dinamicamente a runtime.
Inoltre, come sottolinea utente @Peter Hosey, è possibile utilizzare come ->
Friend
C++ s 'in metodi come copyWithZone
tuttavia, se non si sta facendo cose del genere, quindi stare lontano!
[EDIT]
Inoltre, se si sta cercando di spremere le prestazioni fuori l'oggetto e si sapere quello che stai facendo con quel oggetto o membro allora si potrebbe utilizzare ->
per saltare il overhead del metodo di ricerca. Anche in questo caso, tuttavia, è possibile che si desideri codificare tali sezioni in C o C++ se le prestazioni sono pari a .
Oh, inoltre, non credo che l'uso di ->
sia thread-safe. Se il tuo getter/setter usa @synchronize
usando ->
, ignorerai le protezioni.
fonte
2011-01-19 15:02:03
"Di recente ho è stato esposto a un codice utilizzando un sacco di 'auto->'. .. Girati ... scappare !!!! –