aryaxt / OCMapper

Objective-C library to easily map NSDictionary to model objects, works perfectly with Alamofire. ObjectMapper works similar to GSON
MIT License
347 stars 45 forks source link

Swift Generic in OCMapper #57

Closed terasupernova closed 7 years ago

terasupernova commented 7 years ago

Hi, i want to use generic in class. But i dun know how to get it.

let provider = InCodeMappingProvider()
provider.mapFromDictionaryKey("data", toPropertyKey: "data", withObjectType: BrandSimpleWebModel.self, forClass: PaginationListModel<BrandSimpleWebModel>.self) 
ObjectMapper.sharedInstance().mappingProvider = provider                
let paginationListModel = ObjectMapper.sharedInstance().objectFromSource(response, toInstanceOfClass: PaginationListModel<BrandSimpleWebModel>.self) as! PaginationListModel<BrandSimpleWebModel>
class PaginationListModel<T>: NSObject{
var totalPage: NSNumber!
var totalItem: NSNumber!
var currentPage: NSNumber!
var itemPerPage: NSNumber!
var data: [T]!

When i print "data", the result is nil. If i replace var data:[T]! to var data:[BrandSimpleWebModel]! then i can get the data. Please help me. Thank you

aryaxt commented 7 years ago

hey @terasupernova Unfortunately generics will not work since this library uses objc runtime APIs. you could create a wrapper around it though, something like:

func providePaginatedData<T>(type: T, dictionary: [String: AnyObject]) -> PaginationListModel<T> {
    let model = PaginationListModel<T>()
    model.data = ObjectMapper.sharedInstance().objectFromSource(dictionary, toInstanceOfClass: T) as! [T]
    return model
}

haven't tested or compiled the code so there may be errors in it, let me know if it makes sense LEt me know if this works

terasupernova commented 7 years ago

Hi, @aryaxt. It works, thank you very much.