Reflection error converting to Swift 4 in Objective-C properties - objective-c

Getting error message
Cannot convert value of type 'UnsafeMutablePointer<objc_property_t>?' (aka 'Optional<UnsafeMutablePointer>') to specified type 'UnsafeMutablePointer<objc_property_t?>' (aka 'UnsafeMutablePointer<Optional<OpaquePointer>>')
On this line
let properties : UnsafeMutablePointer <objc_property_t?> = class_copyPropertyList(self.classForCoder, &count)
Full code here
var count = UInt32()
let properties : UnsafeMutablePointer <objc_property_t?> = class_copyPropertyList(self.classForCoder, &count)
var propertyNames = [String]()
let intCount = Int(count)
for i in 0..<intCount {
let property : objc_property_t = properties[i]!
guard let propertyName = NSString(utf8String: property_getName(property)) as? String else {
debugPrint("Couldn't unwrap property name for \(property)")
break
}
propertyNames.append(propertyName)
}

You are getting the error because the return type of class_copyPropertyList is not UnsafeMutablePointer<objc_property_t?>.
Your line should read
let properties : UnsafeMutablePointer <objc_property_t> = class_copyPropertyList(self.classForCoder, &count)

class_copyPropertyList() returns a UnsafeMutablePointer<objc_property_t>? and not a UnsafeMutablePointer<objc_property_t?>. It is usually better to avoid explicit type annotations and just write
let properties = class_copyPropertyList(self.classForCoder, &count)
and let the compiler infer the type. The optional must then be unwrapped, for example with guard:
guard let properties = class_copyPropertyList(self.classForCoder, &count) else {
return // Handle error ...
}
The Swift String creation can also be simplified, leading to
var count = UInt32()
guard let properties = class_copyPropertyList(self.classForCoder, &count) else {
return
}
var propertyNames = [String]()
for i in 0..<Int(count) {
let propertyName = String(cString: property_getName(properties[i]))
propertyNames.append(propertyName)
}

You can remove type annotation, like so:
var count = UInt32()
let properties = class_copyPropertyList(self.classForCoder, &count)
Now the properties can also be mapped:
if let properties = class_copyPropertyList(self.classForCoder, &count) {
let range = 0..<Int(count)
let names = range.map {
String(cString: property_getName(properties[$0]))
}
}

Related

iOS - Realm Query is not working properly

I am using Swift(2.2) Realm Framework as doing with document. Here is my codes.
class SwipedAsset: Object{
dynamic var identifier = ""
dynamic var createdAt = ""
}
// save data
let realm = try! Realm()
let fileName = asset.originalFilename
if fileName != nil {
let swipedAssets = realm.objects(SwipedAsset.self).filter("identifier == '\(fileName!)'")
let assetCount = swipedAssets.count
if assetCount == 0 {
let swipedAsset = SwipedAsset()
if asset.originalFilename != nil {
swipedAsset.identifier = asset.originalFilename!
}
if asset.creationDate != nil {
let year = String(asset.creationDate!.year)[2...3]
let key = "\(asset.creationDate!.monthName) \(year)"
swipedAsset.createdAt = key
}
let realm = try! Realm()
try! realm.write{
realm.add(swipedAsset)
}
}
}
// load data
let realm = try! Realm()
let swipedAssets = realm.objects(SwipedAsset.self).filter("createdAt == '\(key)'")
let lastObject = swipedAssets.last
print(lastObject.identifier)
print(lastObject.createdAt)
Here, values are all "", "" Nothing, But swipedAssets.count = 3 I thought it means realm's query is working properly.
What's wrong with me ? Thanks for any help.
Please do not try to debug with breakpoint.

NSMutableArray. Objective-c to swift code

I'm trying to convert this Objective-C code to swift, but can't seem to figure it out:
#implementation MultiplayerNetworking {
uint32_t _ourRandomNumber;
GameState _gameState;
BOOL _isPlayer1, _receivedAllRandomNumbers;
NSMutableArray *_orderOfPlayers;
#define playerIdKey #"PlayerId"
#define randomNumberKey #"randomNumber"
- (id)init
{
if (self = [super init]) {
_ourRandomNumber = arc4random();
_gameState = kGameStateWaitingForMatch;
_orderOfPlayers = [NSMutableArray array];
[_orderOfPlayers addObject:#{playerIdKey : [GKLocalPlayer localPlayer].playerID, randomNumberKey : #(_ourRandomNumber)}];
}
return self;
}
};
This is what I thought I would be, but I'm no sure at all, so I would appreciate som help here.
class MultiplayerNetworking {
var _ourRandomNumber = uint32_t()
var _gameState = GameState()
var isPlayer1 = false
var receivedAllRandomNumbers = false
var orderOfPlayers = [AnyObject]()
let playerIdKey = "PlayerId"
let randomNumberKey = "randomNumber"
override init() {
super.init()
self.ourRandomNumber = arc4random()
self.gameState = kGameStateWaitingForMatch
self.orderOfPlayers = [AnyObject]()
orderOfPlayers.append([playerIdKey: GKLocalPlayer.localPlayer().playerID, randomNumberKey: ourRandomNumber])
}
}
But it gives me some errors, a lot:
I used this converter: objectivec2swift.com since I have no experience with Objective-C
enum GameState {
case waitingForMatch
}
class MultiplayerNetworking {
var isPlayer1 = false
var receivedAllRandomNumbers = false
var orderOfPlayers = [AnyObject]()
private let playerIdKey = "PlayerId"
private let randomNumberKey = "randomNumber"
private var ourRandomNumber = arc4random()
private var gameState = GameState.waitingForMatch
init() {
orderOfPlayers.append([playerIdKey: GKLocalPlayer.localPlayer.playerID, randomNumberKey: ourRandomNumber] as AnyObject)
}
}
I am assuming that GameState is an enum, and have made the enum with just the one case I can see from your code. I am also guessing that variables starting with an underscore are supposed to be private instance variables of that class, so I have made them private here. Instead of initializing everything in init, I have made use of Swift to give all the properties initial values.
class MultiplayerNetworking {
var _ourRandomNumber = [__uint32_t]()
var _gameState = GameState()
var isPlayer1 = false
var receivedAllRandomNumbers = false
var orderOfPlayers = [AnyObject]()
let playerIdKey = "PlayerId"
let randomNumberKey = "randomNumber"
init() {
self.ourRandomNumber = arc4random()
self.gameState = kGameStateWaitingForMatch
self.orderOfPlayers = [AnyObject]()
orderOfPlayers.append([playerIdKey: GKLocalPlayer.localPlayer().playerID, randomNumberKey: ourRandomNumber])
}
}
Try using this code
class Player{
var playerIdKey : String?
var randomNumberKey : UInt32?
}
class MultiplayerNetworking {
var ourRandomNumber = UInt32()
var gameState = GameState()
var isPlayer1 = false
var receivedAllRandomNumbers = false
var orderOfPlayers = [Player]()
let playerIdKey = "PlayerId"
let randomNumberKey = "randomNumber"
override init() {
self.ourRandomNumber = arc4random()
self.gameState = kGameStateWaitingForMatch
let player = Player()
player.playerIdKey = GKLocalPlayer.localPlayer().playerID
player.randomNumberKey = ourRandomNumber
orderOfPlayers.append(player)
}
}
I would recommend that you create a separate class for player in the previous code the variable was an array type of AnyObject and a tipple was being appended to it so the compiler was complaining. So create a separate player class and set its properties and then append it to your array and your code should run fine.I also removed override keyword from init as there is no super class for this class.

Custom object to NSDictionary or NSData

Guys i am new to iOS development hardly 2 weeks, i want to convert custom object to NSDictionary or NSData. I want to pass that complex object to web API to get and save.
class customClass{
var firstName:String?
var lastName:String?
var services:Services
}
class Services{
var list:[String] = [String]()
}
can somebody help me to resolve this please.
A bit late... try this in playground. Please note that it will not handle NSData correctly. Also, for the code to work, you need to make sure that your custom class inherits from NSObject and adheres to protocol Parsable. That is because you need to make use of the Objective C runtime for this solution to work with classes. Furthermore all your objects need to be subclasses of NSObject (e.g. NSArray instead of Swift type Array).
import UIKit
protocol Parsable {
}
// Define classes as NSObjects
class customClass: NSObject, Parsable {
var firstName:String?
var lastName:String?
var services:Services?
}
class Services: NSObject, Parsable {
var list:NSMutableArray = NSMutableArray()
}
// Create objects
var obj = customClass()
obj.firstName = "My"
obj.lastName = "Name"
var serv = Services()
serv.list = NSMutableArray()
serv.list.addObject("AAA")
serv.list.addObject("BBB")
obj.services = serv
// The magic
func parse(o: NSObject) -> AnyObject {
let aClass : AnyClass? = o.dynamicType
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass : UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(aClass, &propertiesCount)
let propertiesDictionary : NSMutableDictionary = NSMutableDictionary()
if propertiesCount == 0 {
if let a = o as? [NSObject] {
return a.map( {parse($0)} )
} else {
// Take into account NSData here!!!
return o
}
} else {
for var i = 0; i < Int(propertiesCount); i++ {
let property = propertiesInAClass[i]
let propertyName = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding) as! String
let propertyValue : AnyObject = o.valueForKey(propertyName)!;
if propertyValue is NSObject && propertyValue is protocol<Parsable> {
propertiesDictionary.setValue(parse(propertyValue as! NSObject), forKey: propertyName)
} else {
propertiesDictionary.setValue(propertyValue, forKey: propertyName)
}
}
return propertiesDictionary
}
}
print(parse(obj))
//print(parse(obj.services!))
//print(parse(obj.services!.list))

Swift global variable

I'm new in swift.
I would like to figure out how to reuse this variable (item) in other ways:
if var item = currentItem?.listCategoryScheme[countCategoryScheme].listCategory{
...
}
I tried to do this:
var item:NSObject?
func{
if item = currentItem?.listCategoryScheme[countCategoryScheme].listCategory{
...
}
} func2{
//here reuse item
}
but does not work
Thanks
Declare your variable like:
var iteam : NSObject = NSObject()
In ViewController class.
var itemGlobal:String = String()
func printItem(item: String)
{
println(item)
itemGlobal = item
}
func printGlobalItem()
{
println(itemGlobal)
}
printItem("Swift") //prints "Swift" and assignes the itemGlobal to "Swift"
printGlobalItem() //prints "Swift", from the itemGlobal, previously assigned

Get Property List of Swift Class

I am trying to get the property list of a swift class. There is a similar question here and here. I have everything working except for certain types do not get returned from class_copyPropertyList. The ones I have tested it with so far are Int? and enums. I have an example class below of what I am trying.
enum PKApiErrorCode: Int {
case None = 0
case InvalidSignature = 1
case MissingRequired = 2
case NotLoggedIn = 3
case InvalidApiKey = 4
case InvalidLogin = 5
case RegisterFailed = 6
}
class ApiError: Serializable {
let code: PKApiErrorCode?
let message: String?
let userMessage: String?
init(error: JSONDictionary) {
code = error["errorCode"] >>> { (object: JSON) -> PKApiErrorCode? in
if let c = object >>> JSONInt {
return PKApiErrorCode.fromRaw(c)
}
return nil
}
message = error["message"] >>> JSONString
userMessage = error["userMessage"] >>> JSONString
}
}
And the Serializable class (with some help from https://gist.github.com/turowicz/e7746a9c035356f9483d is
public class Serializable: NSObject, Printable {
override public var description: String {
return "\(self.toDictionary())"
}
}
extension Serializable {
public func toDictionary() -> NSDictionary {
var aClass : AnyClass? = self.dynamicType
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass : UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(aClass, &propertiesCount)
var propertiesDictionary : NSMutableDictionary = NSMutableDictionary()
for var i = 0; i < Int(propertiesCount); i++ {
var property = propertiesInAClass[i]
var propName = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding)
var propType = property_getAttributes(property)
var propValue : AnyObject! = self.valueForKey(propName);
if propValue is Serializable {
propertiesDictionary.setValue((propValue as Serializable).toDictionary(), forKey: propName)
} else if propValue is Array<Serializable> {
var subArray = Array<NSDictionary>()
for item in (propValue as Array<Serializable>) {
subArray.append(item.toDictionary())
}
propertiesDictionary.setValue(subArray, forKey: propName)
} else if propValue is NSData {
propertiesDictionary.setValue((propValue as NSData).base64EncodedStringWithOptions(nil), forKey: propName)
} else if propValue is Bool {
propertiesDictionary.setValue((propValue as Bool).boolValue, forKey: propName)
} else if propValue is NSDate {
var date = propValue as NSDate
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "Z"
var dateString = NSString(format: "/Date(%.0f000%#)/", date.timeIntervalSince1970, dateFormatter.stringFromDate(date))
propertiesDictionary.setValue(dateString, forKey: propName)
} else {
propertiesDictionary.setValue(propValue, forKey: propName)
}
}
return propertiesDictionary
}
public func toJSON() -> NSData! {
var dictionary = self.toDictionary()
var err: NSError?
return NSJSONSerialization.dataWithJSONObject(dictionary, options:NSJSONWritingOptions(0), error: &err)
}
public func toJSONString() -> NSString! {
return NSString(data: self.toJSON(), encoding: NSUTF8StringEncoding)
}
}
The String seem to only appear if the Optionals are valid values and the code never appears on the object if it is an enum or Int unless the Int has a default value.
Thanks for any advice I can get for getting all properties of a class no matter what they are.
I got a response on the apple developer forums regarding this issue:
"class_copyPropertyList only shows properties that are exposed to the Objective-C runtime. Objective-C can't represent Swift enums or optionals of non-reference types, so those properties are not exposed to the Objective-C runtime."
Source
So, in summary, serialization to JSON using this approach is not currently possible. You might have to look into using other patterns to accomplish this, such as giving the task of serialization to each object, or potentially by using the reflect() method to serialize an object to JSON.