I’m not sure if I used the correct terms, please understand I just started experimenting with objective yesterday and I came from a c# background so I might use some c# terms.
With that said. I have two classes. 1 main class which uses the other class as a property:
@class Fighter;
@interface Match : NSObject{
int Id;
Fighter *Fighter;
int FScore;
}
@property int Id, FScore;
@property Fighter *Fighter;
@end
*implementation:
@implementation Match
@synthesize Id, FScore, Fighter;
@end
This is the class referenced:
@interface Fighter : NSObject{
int Id;
NSString *Name;
}
@property int Id;
@property NSString *Name;
@end
@implementation Fighter
@synthesize Id, Name;
@end
Now this is how I would create an instance of the object
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
Match *match = [[Match alloc]init];
match.Id = 1;
match.Fighter = [[Fighter alloc]init];
match.Fighter.Id = 9;
match.Fighter.Name = @"womp";
}
Now, I was wondering if there’s like a shortcut in assigning the values for the Fighter instance. As in c# you can do something like so:
match.Fighter = new Fighter{ Id = 9, Name = "womp" };
Wanted to know just in case I may add several more properties to that class or to any other class.
PS.
Is it better to use [[Class alloc] init] than [Class new]??
Thanks!!!
The typical way to do this in Objective-C is to create a custom
-initmethod with arguments for properties to be initialized. So you might have a-[Fighter initWithID:name:]method:Then you create your fighter object with:
A couple comments on your code. In Objective-C it is convention to begin property names with a lowercase letter. The exception is if the name of the property is an acronym like ‘ID’ or ‘URL’, in which case you make it all uppercase. This same is true of method and variable names. Capitalized names are reserved for types including class names (e.g. ‘Fighter’).
Regarding your P.S. question,
+newjust calls alloc then init and returns the result, so they’re exactly equivalent. That said, +new is not really commonly used among Objective-C programmers, and you’ll see alloc/init used much more frequently.Finally, assuming you’re deploying to a target using the modern Objective-C runtime (10.6+ and 64-bit) you don’t need to explicitly declare instance variables to back your @properties, because the compiler will synthesize (create) them for you. With recent versions of Xcode (4.4 and higher), you don’t even need the @synthesize statements, because the compiler will insert those for you too. The @property statement is all you need.