0

I'd like to add an ivar to an existing objective-c class in runtime, but documentation states that an ivar cannot be an existing class, so I think property could still solve my issue.

As stated here class_addProperty(...) returns true, but when I try to access the ivar by it's name (or the property name) it always returns nil. What could be the issue causing this to happen?

Community
  • 1
  • 1
Mercurial
  • 2,095
  • 4
  • 19
  • 33
  • 2
    On the surface this strikes me as a bad idea.. what is the reasoning behind wanting to add it at runtime? – Ben Jul 26 '13 at 18:59
  • this is the kind of question where you need to show your code, what are you doing for your getter and setter? – Michael Dautermann Jul 26 '13 at 19:01
  • @Ben - because class is a part of a framework and I don't have access to it's source. I can extend the class and add properties, but I was trying something different since I'm not sure if subclassing it can affect workflow of the framework. – Mercurial Jul 26 '13 at 19:59
  • @Michael - I've tested on the exactly the same code I've posted the link for. It's an accepted answer and I thought it'd work. – Mercurial Jul 26 '13 at 20:00
  • why dont you make a wrapper class that holds the ivar that you want and also holds the original class you were trying to add to – Ben Jul 29 '13 at 15:04

2 Answers2

1

You won't be able to add an ivar to the class at runtime. You can think of the class, and its ivars, as something like a C struct. It's layout is defined at compile time.

You can add properties at runtime (since these are just methods), and you can implement their getters and setters, but you'll need to come up with a different way to store any data that they represent.

adpalumbo
  • 3,031
  • 12
  • 12
  • If you're right, it makes perfect sense then. For the sake of argument, would I be able to change the structure in compile time somehow? :) I've read a bit about it, and the documentation states (about class_addIvar): "This function may only be called after objc_allocateClassPair and before objc_registerClassPair. Adding an instance variable to an existing class is not supported." – Mercurial Jul 26 '13 at 20:02
  • 1
    I'm not sure what you'd need to do at compile-time? You could do some magic with macros or C++ templates, but I doubt it would apply to many real-world scenarios. If you really need to create a class dynamically, or are just curious about the theoretical workings of Objective-C, this is probably the best available guide: http://www.mikeash.com/pyblog/friday-qa-2010-11-6-creating-classes-at-runtime-in-objective-c.html – adpalumbo Jul 26 '13 at 20:10
0

Are you looking for something similar with some other programming language?

it looks like adding properties in AS3, but objc think the best would you use to store NSDictionary objects by keys.

Elto
  • 420
  • 3
  • 11