Search code examples
iosswiftswift-extensions

New stored property always returns nil | iOS Swift


A new stored property created for exisiting class using extension. While getting value its always returning nil value. The below code is what i tried to add new stored property.

var IdentifiableIdKey   = "kIdentifiableIdKey"
extension EKEvent {
    
    public var customId: Int {
        get {
            return (objc_getAssociatedObject(self, &IdentifiableIdKey) as? Int) ?? 0
        }
        set {
            print("\(newValue)")
            objc_setAssociatedObject(self, &IdentifiableIdKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
}

Utilisation

let eventStore = EKEventStore()
let calendars = eventStore.calendars(for: .event)

for calendar in calendars {
    
       if calendar.title == "Events" {
                                    
         let oneMonthAgo = NSDate(timeIntervalSinceNow: -30*24*3600)

         let oneMonthAfter = NSDate(timeIntervalSinceNow: +30*24*3600)
                            
         let predicate = eventStore.predicateForEvents(withStart: oneMonthAgo as Date, end: oneMonthAfter as Date, calendars: [calendar])
                            
         let events = eventStore.events(matching: predicate)
                                    
           for event in events {                                        
                print("evnet id \(event.customId)")

                }
             }
          }

Somebody help me to find the mistake I did. Thanks in advance.


Solution

  • The fact is that objc_getAssociatedObject/objc_setAssociatedObject assign a value to an object instance so it can be alive with this instance only. Since your custom property is not serialised by EventKit it's naturally that new obtained instances of events after the request have no associated objects.