我已经在Java和.Net中编程了一段时间,但从未真正使用过C或Objective C.我仍然试图理解一些概念。我正在研究一个简单的程序,看看我如何制作一组结构。我相信我做对了。我很难搞清楚如何访问子类并将值存储到我创建的子类中。
因为我使用了scanf,所以我猜错了。任何人都可以提供任何帮助吗?
这是我到目前为止所拥有的。
#import <Foundation/Foundation.h>
//Player Prototype: Stores name and wins so far. It can also print out the name and wins
@interface Player : NSObject
{
NSString *name; //Player name
NSInteger wins; //Player wins
NSInteger losses; //Player losses
NSInteger bp; //extra value for anything I might need in the future.
}
@property (retain, nonatomic) NSString *name;
@property NSInteger wins;
@property NSInteger losses;
@property NSInteger bp;
@end
//Next part
@implementation Player
@synthesize name;
@synthesize wins;
@synthesize losses;
@synthesize bp;
@end
//Brackets
@interface Bracket : NSObject
{
NSMutableArray *playerarray;
Player *addplayer;
}
@property (retain, nonatomic) NSMutableArray *playerarray;//array of players
@property (retain, nonatomic) Player *addplayer;//player and data
-(void) SetUp;
@end
//Starting Bracket, working with only 8. Later moving up to 32
@implementation Bracket
@synthesize playerarray;
@synthesize addplayer;
-(void) SetUp;//sets up the array
{
int i;//counting fun!
playerarray = [[NSMutableArray alloc] init];//initialize a bracket
for(i = 0; i < 8; i++)//To add the players
{
Player *addplayerx = [Player new];//New instance of Player
NSString *p;//Not sure if I need two of them.
NSString *tempname = @"bye";
NSLog(@"Player %d Name:", i);
scanf("%s",&p);
tempname = p;
NSLog(@"%s", tempname);
addplayerx.name = p;
NSLog(@"%s", addplayerx.name);
addplayerx.wins = 0;
addplayerx.losses = 0;
addplayerx.bp = 0;
[playerarray addObject: addplayerx];
[addplayerx release];
[p release];
}
}
@end
//End function
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Bracket *starting = [Bracket new];
[starting SetUp];
[pool drain];
return 0;
}
答案 0 :(得分:4)
您不能scanf()
加入NSString
。你需要扫描一个常规的C字符串(确保你为它分配内存),然后你可以使用NSString
构建stringWithUTF8String:
,或者沿着那些线构建。{/ p>
答案 1 :(得分:2)
不要猜测:在调试器下运行应用程序,当它崩溃时,检查回溯。您还可以查看〜/ Library / Logs / DiagnosticReports / foo.crash中的回溯。
你想做什么,从文件中逐行读取数据?在所有换行符上使用text = [NSString stringWithContentsOfFile:path]
然后拆分text
会容易得多:
NSCharacterSet *newlines = [NSCharacterSet newlineCharacterSet];
NSArray *lines = [text componentsSeparatedByCharactersInSet:newlines];
然后你可以循环并抓住玩家名称:
NSMutableArray *players = [NSMutableArray arrayWithCapacity:[lines count]];
NSString *whitespace = [NSCharacterSet whitespaceCharacterSet];
for (NSString *line in lines) {
NSString *name = [line stringByTrimmingCharactersInSet:whitespace];
Player *player = [[[Player alloc] init] autorelease];
player.name = name;
[players addObject:player];
}