Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert NSString to plain Objective C code

For example I have

NSString *string = @"return sharedInstance;";

I have a class method

+ (id)sharedInstance;

Can I convert that string to plain code and use it in my method? This would be extremely useful for debugging. Suppose I have a method where I want to test some code (Let it be simple return values, Is it possible?) I can just write code for the method and test the new code in runtime.

like image 669
s6luwJ0A3I Avatar asked Feb 16 '13 12:02

s6luwJ0A3I


People also ask

What is NSString in Objective C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

Is NSString UTF 8?

An NSString object can be initialized from or written to a C buffer, an NSData object, or the contents of an NSURL . It can also be encoded and decoded to and from ASCII, UTF–8, UTF–16, UTF–32, or any other string encoding represented by NSStringEncoding .

What is NSString in swift?

NSString : Creates objects that resides in heap and always passed by reference. String: Its a value type whenever we pass it , its passed by value. like Struct and Enum, String itself a Struct in Swift.


2 Answers

Objective C on iOS is a compiled language; The code is interpreted and translated to machine code long before you run your application. Running objective C in a dynamic manner like this is not possible. For this you're gonna need a dynamic language.

like image 99
TinkerTank Avatar answered Sep 29 '22 08:09

TinkerTank


What you've described isn't exactly possible. But there is support for certain things, eg, the ability to instantiate classes and invoke methods (theoretically) with strings:

NSClassFromString allows you to instantiate classes based on a passed string.

NSSelectorFromString allows you to invoke or 'call' a method based on passed string.

The string can be determined dynamically at run-time.

Based on your comments this is apparently not what you're interested in (despite the fact I think it does actually address your question). One thing you can do (it's not native Obj-C, but I think it is pertinent given some of the comments) is to inject JavaScript into a UIWebView.

like image 30
isaac Avatar answered Sep 29 '22 07:09

isaac