如何在Swift中编写initwithcoder代码?

时间:2015-11-30 02:39:27

标签: swift initwithcoder

我是swift adn中的新手我在swift中遇到initwithcoder问题。

我有类UserItem,我需要它来保存用户登录。

目标c中的

就像这样

import java.util.Scanner;
public class Assignment7 {

    public static int row, col;
    public static Scanner scan = new Scanner(System.in);
    public static char[][] board = new char[3][3];
    public static char turn = 'X';
    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        /*create for-loop
     * 9 empty spots, 3x3
         */

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                board[i][j] = '_';
            }
        }
        Play();
    }

    public static void Play() {
        //find if game over
        boolean playing = true;
        PrintBoard();

        while (playing) {
            System.out.println("Please enter a row, then a column: ");
            //make row next thing player types
            row = scan.nextInt() - 1;
            //same with column
            col = scan.nextInt() - 1;
            board[row][col] = turn;
            if (GameOver(row, col)) {
                playing = false;
                System.out.println("Game over! Player " + turn + " wins!");

            }
            PrintBoard();
            //switch players after entries
            if (turn == 'X') {
                turn = 'O';
            } else {
                turn = 'X';
            }
        }

    }

    public static void PrintBoard() {

        for (int i = 0; i < 3; i++) {
            System.out.println();
            for (int j = 0; j < 3; j++) {
                //get dividers on left
                if (j == 0) {
                    System.out.print("| ");
                }
                // get dividers in all
                System.out.print(board[i][j] + " | ");
            }
        }
        //enter space after board
        System.out.println();
    }

    public static boolean GameOver(int rMove, int cMove) {
        // Check perpendicular victory
        if (board[0][cMove] == board[1][cMove]
                && board[0][cMove] == board[2][cMove]) {
            return true;
        }
        if (board[rMove][0] == board[rMove][1]
                && board[rMove][0] == board[rMove][2]) {
            return true;
        }
        // Check diagonal victory
        if (board[0][0] == board[1][1] && board[0][0] == board[2][2]
                && board[1][1] != '_') {
            return true;
        }
        return false;

    }
}

在swift中,我试着这样做

 - (id)initWithCoder:(NSCoder *)decoder{
    if (self = [super init]){
        self.username = [decoder decodeObjectForKey:@"username"];
    }
    return self;
}

但如果像上面那样,我会收到代码错误

override init() {
   super.init()
}    

required init(coder decoder: NSCoder!) {

   self.username = (decoder.decodeObjectForKey("username")?.stringValue)!

   super.init(coder: decoder)
}

错误信息是&#34;额外的参数&#39;编码器&#39;在电话中

我无法理解,所以我试试这段代码,

super.init(coder: decoder)

但是,得到错误

convenience init(decoder: NSCoder) {
   self.init()

   self.username = (decoder.decodeObjectForKey("username")?.stringValue)!
}

我该怎么办?谢谢你的帮助。

1 个答案:

答案 0 :(得分:12)

我在过去与NSCoding(你用来归档和取消归档对象的协议)进行了斗争,我发现你正在经历同样的痛苦。希望这会减轻一点:

class UserItem: NSObject, NSCoding {
    var username: String
    var anInt: Int

    init(username: String, anInt: Int) {
        self.username = username
        self.anInt = anInt
    }

    required init?(coder aDecoder: NSCoder) {
        // super.init(coder:) is optional, see notes below
        self.username = aDecoder.decodeObjectForKey("username") as! String
        self.anInt = aDecoder.decodeIntegerForKey("anInt")
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // super.encodeWithCoder(aCoder) is optional, see notes below
        aCoder.encodeObject(self.username, forKey: "username")
        aCoder.encodeInteger(self.anInt, forKey: "anInt")
    }

    // Provide some debug info
    override var description: String {
        get {
            return ("\(self.username), \(self.anInt)")
        }
    }
}

// Original object
let a = UserItem(username: "michael", anInt: 42)

// Serialized data
let data = NSKeyedArchiver.archivedDataWithRootObject(a)

// Unarchived from data
let b = NSKeyedUnarchiver.unarchiveObjectWithData(data)!

print(a)
print(b)

重要的是匹配encodeWithCoder(aCoder:)(归档函数)和init(coder:)(unarchive函数)中的键和数据类型。

初学者的困惑在于如何处理超类。如果超类本身符合NSCoding,则只应在上述两个函数中包含超类。 NSObject本身不提供。这个想法是每个类都知道它自己的属性,其中一些是私有的。如果超类无法归档/取消归档,则无需调用它们。