我是新的iOS开发者。我开始学习Swift但我想切换到Objective-C。下面是我在Swift中使用的代码
我有Player.swift
:
import Foundation
import UIKit
struct Player {
var name: String!
var game: String!
var rating: Int
init(name:String?, game:String?, rating:Int) {
self.name = name
self.game = game
self.rating = rating
}
}
我有一个类存储数据播放器对象数据,这个数据在项目的任何地方使用:
import Foundation
let playerData = [
Player(name: "Bill Evan", game: "call of duty", rating: 4),
Player(name: "Linh Nguyen", game: "Alien vs predator", rating: 3)
]
我的问题是如何在Objective-C中做到这一点:
我正试图在Player.h
中执行此操作:
#import <Foundation/Foundation.h>
@interface Player : NSObject
@property(nonatomic, strong) NSString *name;
@property(nonatomic, strong) NSString *game;
@property int rating;
-(id)initWithPlayer:(NSString *)name
game:(NSString*)game
rating:(int)rat;
@end
在Player.m
:
#import "Player.h"
@implementation Player
-(id)initWithPlayer:(NSString *)name game:(NSString *)game rating:(int)rating {
self.name = name;
self.game = game;
self.rating = rating;
return self;
}
@end
如何创建Player对象的数组存储许多玩家对象?
答案 0 :(得分:2)
使用类型化数组NSArray<Player *>
,以便在访问时不必强制转换元素,如果您尝试插入非Player
对象,编译器会发出警告。
NSArray<Player *> *players = @[
[[Player alloc] initWithPlayer:@"Steven" game:@"Pokémon Go" rating:100],
[[Player alloc] initWithPlayer:@"Mike" game:@"Pokémon Silver" rating:90]
];
Player *steven = players[0];
steven.rating = steven.rating + 1;
如果你这样做
NSArray *players = @[ ... see above ... ];
你必须像这样施展
Player *steven = (Player *)players[0];
这也更危险,因为编译器也允许你这样做:
NSArray *players = @[
[[Player alloc] initWithPlayer:@"Steven" game:@"Pokémon Go" rating:100],
@"Just a String, not a Player object"
];
当您将@"Just a String, ..."
对象(players[1]
)转换为Player对象时,这显然会导致运行时崩溃。
答案 1 :(得分:0)
要回答这个问题,您可以使用以下两种方法之一初始化Objective-C / Foundation中的对象数组:
// Original, longer way of doing it
NSArray *words = [NSArray arrayWithObjects:@"list", @"of", @"words"];
// Modern Objective-C shorthand
NSArray *words = @[@"list", @"of", @"words"];
稍微冗长一点,但鉴于你的对象,这里是你的Swift代码:
let playerData = [
Player(name: "Bill Evan", game: "Call of Duty", rating: 4),
Player(name: "Linh Nguyen", game: "Alien vs. Predator", rating: 3)
]
看看Objective-C:
NSArray *playerData = @[
[[Player alloc] initWithPlayer:@"Bill Evan" game:@"Call of Duty" rating:4],
[[Player alloc] initWithPlayer:@"Linh Nguyen" game:@"Alien vs. Predator" rating:3]
];