如何使用NSKeyedArchiver在iOS中复制按钮

问题描述 投票:0回答:1

要复制按钮,此方法工作正常:

   NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: btn];
   UIButton *newButton = [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];

但是自iOS12起,已弃用。但是使用建议的方法会使newButton为nil。我在做什么错了,或者确实有另一种方法可以复制UIButton。完整代码:

// Init originalBtnsArray and
originalBtnsArray = [[NSMutableArray alloc]init];

// Populate originalBtnsArray
for (UIButton *btn in btnsReferencesArray){
    // Below works but is now deprecated as of iOS 12
    //NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: btn];
    //UIButton *newButton = [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];

    NSError* error = nil;
    NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:btn requiringSecureCoding:NO error:&error];

    NSError* unArchiveError = nil;
    UIButton *newButton = [NSKeyedUnarchiver unarchivedObjectOfClass:[UIButton class] fromData:archivedData error:&unArchiveError];

    // newButton is nil, which is suboptimal
    [originalBtnsArray addObject:newButton];
}
ios objective-c
1个回答
0
投票

现在就可以使用:

UIButton *newButton = [[UIButton alloc]init];
newButton.frame = btn.frame;
[originalBtnsArray addObject:newButton];
热门问题
推荐问题
最新问题