0

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.

Code cracker
  • 3,105
  • 6
  • 37
  • 67

3 Answers3

2

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.

iUrii
  • 11,742
  • 1
  • 33
  • 48
  • so what is the solution? – Code cracker Sep 15 '20 at 10:15
  • You can look at this answer - https://stackoverflow.com/questions/32550287/how-to-add-some-additional-fields-to-ekevent. Or also you can try to make your second store e.g. dictionary that maps `eventIdentifier` to your custom data but in this way you should synchronise all changes each time programatically. – iUrii Sep 15 '20 at 10:27
-2

Extensions in Swift can add computed instance properties and computed type properties only https://docs.swift.org/swift-book/LanguageGuide/Extensions.html

Roman Ryzhiy
  • 1,540
  • 8
  • 5
-2

It's called objc_setAssociatedObject. See the "Object" at the end? An Int is not an object. Turn your newValue into an NSNumber so you have an object. So that is definitely not going to work.

If your class is not an @objc class that might be a problem.

gnasher729
  • 51,477
  • 5
  • 75
  • 98