I have a Swift class User
and a Swift class Artist
. A User
can have many Artists
and this relationship and these classes are implemented in the code below.
我有一个Swift级的用户和一个Swift类的艺术家。用户可以有许多艺术家和这种关系,这些类是在下面的代码中实现的。
import UIKit
class Artist: NSObject {
var name: String
init(name: String) {
self.name = name
}
}
class User: NSObject {
var artists = [Artist]()
var name: String
init(name: String) {
self.name = name
}
}
I need to be able to edit the artists array from Objective C. When I try to add an object to the artists array, Xcode tells me that the artists array is of type NSArray
and cannot be modified. Is there a way to access this array as an NSMutableArray?
我需要能够从Objective c编辑艺术家数组,当我试图向艺术家数组添加对象时,Xcode告诉我,艺术家数组是NSArray类型的,不能修改。是否有方法以NSMutableArray的形式访问这个数组?
1 个解决方案
#1
2
In Objective C, you can just copy the array to a mutable array:
在Objective C中,只需将数组复制到可变数组:
NSMutableArray *mutableArtists = [artists mutableCopy];
[mutableArtists addObject:...]; // Add your objects to mutableArtists or make other changes.
NSArray *artistsToReturn = [mutableArtists copy];
return artistsToReturn;
Alternatively, you could cast your Swift array to be of NSMutableArray type in the class definition, if you are happy for it to work as an NSMutableArray rather than having the usual Swift mutable array characteristics:
或者,您可以将您的Swift数组转换为类定义中的NSMutableArray类型,如果您喜欢它作为一个NSMutableArray而不是具有通常的Swift可变数组特征的话:
var artists : NSMutableArray = [Artist]()
In Swift, you could also instead create an NSMutableArray copy of the array, that you could then access from your Objective-C class instead, if that was more convenient.:
在Swift中,您还可以创建数组的NSMutableArray副本,如果方便的话,您可以从Objective-C类访问该数组。
var mutableArtists = NSMutableArray(artists)
#1
2
In Objective C, you can just copy the array to a mutable array:
在Objective C中,只需将数组复制到可变数组:
NSMutableArray *mutableArtists = [artists mutableCopy];
[mutableArtists addObject:...]; // Add your objects to mutableArtists or make other changes.
NSArray *artistsToReturn = [mutableArtists copy];
return artistsToReturn;
Alternatively, you could cast your Swift array to be of NSMutableArray type in the class definition, if you are happy for it to work as an NSMutableArray rather than having the usual Swift mutable array characteristics:
或者,您可以将您的Swift数组转换为类定义中的NSMutableArray类型,如果您喜欢它作为一个NSMutableArray而不是具有通常的Swift可变数组特征的话:
var artists : NSMutableArray = [Artist]()
In Swift, you could also instead create an NSMutableArray copy of the array, that you could then access from your Objective-C class instead, if that was more convenient.:
在Swift中,您还可以创建数组的NSMutableArray副本,如果方便的话,您可以从Objective-C类访问该数组。
var mutableArtists = NSMutableArray(artists)