2

I want to know if it's possible to create Objective-C literals like NSString, where instead of [[Object alloc] init], and then assigning you can just assign a value to it, such as @"A string".

Obviously NSString is an object because it has methods to manipulate the data in addition, so in theory there should be a way to do it yourself, but I'm not sure where to even go about finding stuff like this.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • Question unclear. NSInteger is a primitive (it's a typedef for long int or similar). NSString is not; it's an object. What exactly is it that you want to do? – matt May 14 '16 at 17:08
  • "you can just assign a value to it" But what value would you assign? – matt May 14 '16 at 17:12

1 Answers1

2

Objective-C is C. The primitive (what I would call scalar) data types are all numbers and are completely defined by the language; you cannot add to them (though you can rename them using typedef. The corresponding literals, such as 1 and "hello", are also part of C.

Similarly, literals like @"howdy" and @[@"howdy"], though defined by Objective-C rather than C, are part of the language and you cannot change or add to them, as the literal syntax is built into the language.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Something like what you describe is possible in Swift, however, where you can make a type conform to one of the built-in `Literal` protocols and thus use a literal where an object of that type is expected. See http://www.apeth.com/swiftBook/ch04.html#_literal_convertibles for an example. This could be a reason for switching for Swift (or at least giving it a try). – matt May 14 '16 at 17:13
  • I think you misinterpret the question. I don't want to change the way the literals are formated or anything like that, I want an object to be able to be assigned a primitive such as an int or a string or an array if possible on definition such as MyNewClass *class = @"Hello" or something similar – SonarSoundProgramming May 14 '16 at 17:14
  • 3
    I think you misinterpret the answer. I'm telling you you can't do that, because `@"Hello"` _is_ a string literal and cannot go where a MyNewClass is expected. But you _can_ do something like this in Swift. There, you've made me say my answer twice, well done. :) – matt May 14 '16 at 17:15
  • Sorry for my confusion. I misread your answer. I will accept this as the answer to my question. A shame that you cant do that in objective c though. I don't really want to go to swift just yet but I will be sure to check this out when I get there – SonarSoundProgramming May 14 '16 at 17:17