Showing posts with label ObjectiveC. Show all posts
Showing posts with label ObjectiveC. Show all posts

Sunday, September 12, 2010

Case for Objective-C++

Forget Objective-C. I mean it. For iOS development, the ideal language is Objective-C++.

I expect plenty of pitch-fork bearing purists who tend to align themselves with the crowd of goto is bad, and overloaded operators are bad to not like what I'm about to suggest. But; as with goto and overloaded operators, like certain medicines, too much can be fatal. I believe programmers can make reasonable decisions to the use of these constructs.

With Objective-C 2.0 came properties. These allowed for easy integration with key-value coding; but there's one problem with it - all properties are public. All methods are public as well. I believe this is bad programming style.

Here's a key to my solution; simple and elegant:
template<class T>
class Auto
{
private:
T m_o;
public:
inline T operator=(T in_o)
{
if (in_o) [in_o retain];
if (m_o) [m_o release];
m_o = in_o;
return m_o;
}
inline T noRetain(T in_o)
{
if (m_o) [m_o release];
m_o = in_o;
return m_o;
}
inline T operator()() const
{
return m_o;
}
inline Auto(T in_o = NULL)
: m_o(NULL)
{ (*this) = in_o; }
inline Auto(const TNS<T> &in_cpy)
: m_o(NULL)
{
(*this) = in_cpy();
}
inline ~Auto()
{
if (m_o) [m_o release];
}
};

Consider how this code nicely takes an an Objective-C object and wraps it in a smart-pointer.  Ensuring that objects get retained and released becomes much more trivial - and a lot less typing.  No need to define a parameter, synthesize, and double-check that it exists in the dealloc.  Why?  Objective-C++ automagically calls the destructor for C++ objects.

Using this is quite simple: Auto<NSString*> m_something; creates your string.  Assign an auto-release string to it (or use the noRetain method) and off you go forgetting about this object.  Assign a new string?  The old one gets automatically released.  Need to call a method?  [m_something() UTF8String]; is a good example.

The good thing?  minimal overhead - the compiler should inline out most, if not all, of the Auto object.  What you're left with are the retains and releases that you'd have normally put in.

A note of caution: only use this object in places where you'd normally ensure an object gets a retain or release.  Do not enthusiastically put it everywhere.  Recall: good things in great quantities might not be that good.  They can even be fatal!

On the up-side, if you want properties, you'll need to actually write the methods behind to translate from the C++ wrapper.  This is good, you'll see, since it makes it harder to make objects publicly accessible, always a good design decision.

Before I wrap up this post; for private methods, I suggest using C static functions in your implementation files.  Can't get more private than that!

For protected functions - useful with polymorphism - I'd avoid them.  Once a function is declared, it can easily be reflected and used.  No matter how hidden/private it is (unfortunately).  I believe that this poses interesting software design constraints though.

Monday, July 26, 2010

The wonders of NSString

This post is much less of a rant, and more of a regurgitation of how to use NSString as a way to solidify it in my memory and provide a useful way to look it up (I think it'll get buried and I'll forget about this post, making it a form of future e-waste.  Where e-waste is knowledge that accumulates, but serves no purpose in the present except take up space.).

So... the lowly NSString.  Where shall I begin?  Maybe with the simple idea that whatever text processing I needed to do, NSString (and supporting objects) always seems to provide a means to do it (sometimes thanks to methods added after-the-fact to the NSString object).  And also that getting a C string is almost never needed unless interacting with a C library (the standard C library shouldn't be needed).

NSString is very similar (for historical reasons) to Java's String object.  Both can not be changed after being created, changes are rather require the creation of a new object (In such cases - NSAutoReleasePool is your friend if you find yourself doing innumerable string manipulations):
NSAutoreleasePool *p
    = [[NSAutoreleasePool alloc] init];
//Do plenty of string operations using
//[NSString string*] methods.
[p release];

That's the beginning. Ok; time for some fun! Let's say there are plenty of string constants that need to be internationalized? The simplest solution is to write the following for strings:
NSString *s = NSLocalizedString(@"Hello", @"Greeting String");
If you've set up your translation files correctly (get them using genstrings), then "Hello" is the word to get in the current language, and "Greeting String" is a hint to the translator.

Can we do more with NSString? Of course! splitting, loading a string from a file, and all sorts of other operations can be done.

I'll just note a few objects that can be useful rather than give a complete tutorial on them (the Apple docs are very good).

NSCharacterSet defines a set of unicode characters.  This object provides a quick way to get all white-space, all punctuation, and even all newline character sets.  Very useful when parsing files or breaking up strings.

NSScanner provides a nice way to scan any arbitrary file.  It is much more flexible than the standard C/C++ file operations in that it returns the data (String, float, etc. - even delimited to an NSCharacterSet) and a boolean specifying whether the data was obtained.  This makes parsing more complex files... easier.  (I don't doubt that it can be done in C/C++ - just that assuming the structure might vary rather than be fixed is a nice one.  eg.  optional floating-point number would be read as 0 in C++ if memory serves.)

NSXMLParser is nice - but I'm not really a fan of XML.  Let's say that there are neater ways to represent data than XML.  XML is nice for being standard - but the tags are just too much for me.  But it's there and works great!

NSString can also do everything that the standard C library does.  Just that I don't worry about memory buffer sizes.  I'm not familiar enough with the C++ String class to comment on it.

And for speed, CFString allows quick access to the underlying data:
//Direct cast -
//toll-free-bridge as Apple calls it.
CFStringRef r = (CFStringRef)@"NSString";
CFStringLineBuffer b; //... inline buffer used to iterate...
So yes - this has devolved into a rant. It's conclusion: look at what NSString does. It does a lot more than what you think. Especially thanks to categories that allow for any programmer to give NSString more functionality (that's how it can render text to views - and how external libraries could use it - to render strings to textures, etc.).

Unfortunately, this is true of most modern APIs - and for all objects. That is; the objects can do so much. It's no longer a question of knowing how to do something - but knowing the magic keyword that will return the proper function in a search result.

OK, a mini-rant,

<rant>
Programmers now work at such a high-level. And that high-level will allow us to keep on coding as normal while everything transparently becomes parallel (something I've been thinking a lot about recently - the challenge may appear great; but in retrospect abstraction makes it easier. As a hint - we parallelize like the CPU does with instructions. Branches are our undoing - yes I'm captain obvious. I think QT Concurrent is the closest to what I'm thinking - but there is a way to provide a sequential API with parallel underpinnings. It already in the form of OpenGL. The real trick - which I'm almost done tinkering with - is how to get modules that don't know about each other communicating in a relevant way in parallel.).
</rant>

Sunday, April 19, 2009

Cocoa Formatters

Every time I play with Cocoa, I'm reminded of how much I enjoy the framework.  It's elegant, easy to use, and usually provides a small, elegant solution to whatever I'm trying to accomplish.

Now here's what I wanted: Something that would only allow numbers to be entered within a text box while retaining compatibility with 10.4 (to code/test on my PowerBook).

My first instinct was to jump to interface builder, and link up a NSNumberFormatter to the NSTextField, launch the app, and watch what happens.  Let's say I wasn't that impressed...  The NSTextField would hog input until the input was valid.  And I didn't want to update a text box like I used to do.  I only wanted valid input as keys were pressed, not something that the user (myself) would have to think twice about as they try to comprehend an error message.

So, trolling the documents I found a nice method "setPartialStringValidationEnabled:". This is nice.  Would do exactly what I wanted with minimal effort - wait, only available in 10.5...

So overloaded NSTextField in objective C, and tried to intercept the keyUp and keyDown messages from NSResponder.  Hoping that if I removed all non-numerical keys from the stream, my little NSTextField would - hopefuly - not get filled with data.  It didn't work.

However, NSTextField is just a front-end to NSTextFieldCell.  So simply replacing the NSTextFieldCell at runtime with my own super-classed machination should work.  Should.  It didn't respond to NSResponder.  A very interesting thing, but where does the input come from.  Cocoa should be easy - there ought to have an easier way to do this - one that wouldn't make the developers from Apple cringe (if ever they were to see it).

So - again another look at NSFormatter.  MacOS, since 10.0, supports a method called 'isPartialStringValid:'  for subclasses of NSFormatter.  After reading the docs a bit, I implemented a simple formatter where this method would only return NO.  And behold, it was impossible to type anything in the NSTextField!  Success!

So here's the complete implementation of my subclass of NSFormatter.  It simply only allows numbers of the form [+,-][0-9]*[.]+[0-9]*.  For rounding reasons, I've limited the number of digits to 12 and used doubles for storage:


@implementation X_NumberFormatter
- (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error
{
int x;
int l = [partialString length];
BOOL foundDecimal = NO;
int curPostDecimal = 0;
for (x=0; x
{
unichar curChar = [partialString characterAtIndex:x];
if (!(curChar >= '0' && curChar <= '9') && curChar != '.' &&
!(x ==0 && (curChar == '+' || curChar == '-')))
return NO;
if (curChar >= '0' && curChar <= '9')
{
curPostDecimal++;
if (curPostDecimal > 12)
return NO;
}
if (curChar == '.')
{
if (foundDecimal)
return NO;
foundDecimal = YES;
}
}
return YES;
}
- (BOOL)getObjectValue:(id *)anObject forString:(NSString *)string errorDescription:(NSString **)error
{
*anObject = [NSNumber numberWithDouble:[string doubleValue]];
return YES;
}
- (NSString *)stringForObjectValue:(id)anObject
{
if (![anObject isKindOfClass:[NSNumber class]])
return nil;
return [NSString stringWithFormat:@"%1.12g", [anObject doubleValue]];
}
@end