0

All I need to add an extra variable to UITextView class .

My First Attempt :

extension UITextView
{
   var id : String
} 

But it gives an error message Extension may not contain stored properties!

Second Attempt :

extension UITextView
{
   var id : String
   {
    get { return self.id }
    set(newValue) { self.id = newValue }
   }
}

But it crushes my app and give an error message Thread 1 : EXC_BAD_ACCESS when I attempt to assign a value in var id .

enter image description here

How can I assign value in var id and print it ?

roy
  • 6,685
  • 3
  • 26
  • 39

3 Answers3

2

All I need to add an extra variable to UITextView class

You can't add stored properties in extension. The only way is to use computed properties and associated objects, but that's ugly. You should rather write a class that inherits UITextView.

If you really can't subclass UITextView, take a look at this answer how to use associated objects with computed properties.

mag_zbc
  • 6,801
  • 14
  • 40
  • 62
  • I tried so called `ugly` way but it says `Use of unresolved identifier OBJC_ASSOCIATION_COPY_NONATOMIC ` , what is wrong here ? – roy Jul 18 '17 at 14:14
  • 2
    @Roy Look [at the answer](https://stackoverflow.com/a/40862150/1226963) for Swift 3. – rmaddy Jul 18 '17 at 14:58
0

No you can't do that, Because properties need storage and adding properties would change the memory structure of the class as well as introduce a whole host of other issues in usability.

Extensions are meant to augment behaviours, not fundamentally change a class. So, If you need to add additional properties to a class you can do that using Subclass that uses Parent class as UITextView

Jaydeep Vora
  • 6,085
  • 1
  • 22
  • 40
0

Using Associated Objects I solved my problems .

Here is my source code (Swift3) . .

import ObjectiveC

var AssociatedObjectHandle: UInt8 = 0

extension UITextView
{
   var id : String
   {
        get
        {
            return objc_getAssociatedObject(self, &AssociatedObjectHandle) as! String
        }
        set
        {
            objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }

   }
}

Thanks mag_zbc and rmaddy for your useful answers !

roy
  • 6,685
  • 3
  • 26
  • 39