I am a total newbie in Objective-C and Xcode (new to programming as well). I am trying to build a simple card game so I created a Cards
class with properties and instance methods and imported its header file into "Viewcontroller.m".
However, I do not understand two things:
Why the NSLog
in the "Cards.m" is not displaying in the console as I compile. But NSLog
in "Viewcontroller.m" displays.
Seems I can not call the Cards
class ( NSMutableArray
) property. Even I initialized it without error in "Cards.m", in "Viewcontroller.m", the array is still empty.
Very appreciate your helps because I am very struggling!
Cards.h:
@interface Cards : NSObject
@property (strong, nonatomic) NSMutableArray* contents;
-(void)makeContents;
@end
Cards.m:
#import "Cards.h"
@interface Cards()
@end
@implementation Cards
@synthesize contents;
-(id)init{
if(self==[super init]){
contents = [[NSMutableArray alloc]initWithCapacity:53];
}
return self;
}
-(void) makeContents{
NSArray* suits = @[@"♥︎",@"♠︎",@"♣︎",@"♦︎" ];
NSArray* ranks = [[NSArray alloc]initWithObjects:@"A",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"J",@"Q",@"K", nil];
for(NSString* suiting in suits){
for(NSString* ranking in ranks){
NSString* cards = [NSString stringWithFormat:@"%@ %@", ranking,suiting];
[contents addObject:cards];
NSLog(@"%@", contents);//not displaying in console
}
}
}
@end
ViewController.m:
#import "ViewController.h"
#import "Cards.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *flipCount;
@property (nonatomic) int numberOfFlip;
@end
@implementation ViewController
-(void)viewDidLoad{
Cards* cards = [[Cards alloc]init];
NSLog(@"%@", cards.contents); //displaying in console, the contents is an empty array still? why??
}
- (IBAction)flipCard:(UIButton *)sender {
}
@end
You create and define the method makeContents
but never actually call it anywhere. Try calling it in your viewDidLoad
method:
-(void)viewDidLoad{
[super viewDidLoad];
Cards* cards = [[Cards alloc]init];
[cards makeContents];
NSLog(@"%@", cards.contents); //displaying in console, the contents is an empty array still? why??
}
You have a few issues.
=
, not ==
to assign self
to [super init]
. Cards init
method should call makeContents
to set itself up. Update your init
method like this:
-(id)init{
self = [super init];
if (self) {
contents = [[NSMutableArray alloc]initWithCapacity:53];
[self makeContents];
}
return self;
}
This also means that makeContents
should only be called by the Cards
class itself. So you should remove the declaration of - (void)makeContents
from the .h file.
Also, using @synthesize
as you have it is unnecessary. Simply remove that line. And try to find a more up-to-date tutorial that doesn't use such outdated code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.