When to use NS_INLINE functions in objective C - ios

I have realized that many people sometimes use NS_INLINE functions in their code. I am curios how they know when to use it and why they use it.
I have read that INLINE functions have less instructions than objective-C functions. I am a bit lost in this area because I don't know too much about C.
Some example that I've seen are these:
NS_INLINE id NilToEmptyString(id obj)
{
return obj ? : #"";
}
NS_INLINE BOOL isRunningTests(void)
I want to use it at some specific places. For example. I need to get all the assets of the Gallery and then check if they have location and date. I would like to do those functions checkLocation and checkDate as inline functions.
Some users have 5000 pictures, with iPhone 4s the time increases until 5 minutes, that is too much. I want to refactor the code and I read that sometimes inline functions is not a bad way.

NS_INLINE is a macro for the __attribute__((always_inline)) compiler directive, which is stronger than the normal inline keyword. Use it only if you're very sure inlining will result in faster code without unnecessary executable bloat.

Related

Design by Contract in Swift

Does Swift provide a native Design by Contract support? I understand that it can be done during runtime through assertions, but could it be done during compile time? Or, are there any external plugins/libraries that do this?
EDIT
By saying "during compile time Design by Contract", I do not mean the library to be an all powerful static analyser that C# has. It would be enough for me if it is something like the one that iContract provides for Java. Let us look at an example:
A DBC code for the square root evaluation in Java using iContract could be written as :
/**
* #pre f >= 0.0
* #post Math.abs((return * return) - f) < 0.001
*/
public float sqrt(float f) { ... }
Now, this keeps my contract as a part of my API specification rather than a part of its implementation which I believe is a cleaner way. The caller will know what his responsibilities are and the callee is setting its expectation, all in albeit clearer manner. Do we have something like this in Swift?
TL;DR
As #Tommy points out in the comments under your question, it would appear that the plain & simple answer to your question is "No, compile time DbC is not currently a feature of Swift".
What's built in right now?
For built-in support for this type of design strategy, you currently have to look at the runtime I'm afraid. Swift appears to prefer runtime assertions for enforcing preconditions currently, although the language seems generally to be putting more emphasis on safety at compile time (more on this below). The global functions assert, assertionFailure, precondition and preconditionFailure are designed to be sprinkled liberally throughout code without impacting release build performance.
Unit tests are, of course, another strategy for checking that API contracts are fulfilled, but these must be thought of and implemented manually, and so are error prone.
Something else that is perhaps interesting to note is that amongst the better documentation comment support of Swift 2, "requires", "precondition" and "postcondition" are recognised markup keywords, such that they are displayed prominently in quick help documentation:
/// - precondition: f >= 0.0
/// - postcondition: abs((return * return) - f) < 0.001
/// - returns: The square root of `f`.
func sqrt(f: Float) -> Float { ... }
So does this emphasis on being able to provide good documentation for API contracts mean that the Swift development team clearly cares about it, and this is a stop-gap until they incorporate something into the syntax in the future, or does it mean that they think this sort of information belongs in the documentation? Pointless postulation, perhaps. Regardless, despite the fact it's not proper DbC, I think it's a handy thing to be aware of right now.
What can I do about it now?
With Objective-C, macros could be used to essentially implement basic DbC, however the lack of macros in Swift means you would have to resort to some kind of function/generics-based wrapper, which I think would look like a really awkward bodge.
Xcode's support for adding custom scripts to a target's build phases – as suggested by #JonShier in the comments – is perhaps the closest you will get to useful & automatic DbC without waiting for the language to (maybe / maybe not) introduce such a feature. With the aforementioned documentation markup keywords, a script that analyses documentation comments to build unit tests could even be incorporated retrospectively to projects with only a small amount of learning/effort on the part of the user. As you say, I think this could make a very interesting project!
Will it be a built-in feature in the future?
It is not clear whether or not native DbC might be incorporated into Swift in the future. Arguably, it is a feature that is well suited to the mission of the Swift language, which is to say that it promotes safer code and reduced risk of runtime errors. Should it become a part of the language, I would suggest that we would be more likely to see them appear as declaration attributes than as interpreted comment markup, for example:
#contract(
precondition = f >= 0.0,
postcondition = abs((return * return) - f) < 0.001
)
func sqrt(f: Float) -> Float { ... }
(But that is just speculation, and of no use to us right now!)
From what I know of the topic, compile-time DbC can be a very complex problem. But who knows... work on the Clang Static Analyzer has certainly shown that there is an underlying desire to drag identification of runtime bugs back to compile time. Perhaps this is the perfect problem to put a Swift static analyser to work on in the future?
I'm not if this is what you're looking for but here is a suggestion you could try maybe.
If you want to define a protocol where you can define the signature of the sqrt function and leave the implementation for other classes or structs to implement at a later point you could do something like the code below:
Note: the the sqrtf is just using the system implementation here.
public protocol Math {
func sqrtf(f: Float) -> Float
}
struct NativeMath: Math {
func sqrtf(f: Float) -> Float {
return sqrt(f)
}
}
println(NativeMath().sqrtf(2))

Include C Library in iOS project

I am working on a project in iOS using Xcode. I want to include a library written in C. But I don't know how to use C library in Objective-C.
Here is the link of Library: https://github.com/bcl/aisparser
Can someone help me?
You're going to hit one obstacle in the form of what's called "name mangling". C++ stores function names in a way not compatible with Obj-C.
Objective-C doesn't implement classes in the same way as C++, so it's not going to like it.
One way around this is to implement a set of simple C functions which call the C++ functions. It'll be a good challenge to keep the number of C functions as low as possible! You'll end up with a nice compact interface! :)
To declare these functions in a C++ file, you'll need to mark them as C with:
extern "C" int function_name(char *blob,int number, double foo) {...}
This disables the standard name-mangling.
Build a header file with the prototypes for all these functions that you can share with your objective C code.
You won't be able to pass classes around in the same way (because your ObjC code can't use them), but you'll be able to pass pointers (although you might have to lie about the types a little).

"const" In Objective-C and Cocos2D: Is It Me, Or Does It Seem To Be Taboo?

I'm not sure if this is the right place to ask this, since it's not really a technical question but more a question of style and coding practices...
I've always ben a fan of using "const" to define variables that will not be changing throughout their lifetime, most especially when they are parameters to functions/methods. This probably stems from my history with C++, where objects could be passed by reference rather than by pointer, but you wanted to ensure that the original value wasn't accidentally altered, either by you or by someone else on your team who was working on the same code snippet.
When looking through the headers for both Objective-C in general and Cocos2d specifically, I've noticed that there is a noticeable lack of use of this item. Now, I'm not against developing code as quickly as possible, and leaving off constraints such as these leave the developer the option to modify values as their code develops and evolves, but there are some instances where I believe that this laxity does not belong.
For example, in Cocos2D/UIKit, the "UIFont fontWithName" method takes "(NSString *)" as the parameter for the font name: does this method really need to reserve the right to alter the original string that was passed in? I personally like to define constant strings as "const" items, and I don't like the necessity of casting these as non-"const" when calling these methods.
Enough proselytizing: My question - Is the direction now moving towards less well-defined interfaces and more towards "lazy references" (which I do not consider to be a derogative term)?
Thanks in advance for any feedback....
Const wouldn't mean anything for Objective C class pointers, because it would have to be overloaded in a very confusing way for Objective C types. This is because there's no way to mark a method as const, as there is in C++, so the compiler could never enforce it.
That said, at my old company, we did declare global string constants using something like:
NSString* const kMyCoolString = #"Hello, world!";
The point being that it at least couldn't be reassigned to something else.
The closest analog in Objective C/Cocoa/Foundation are mutable/immutable versions of data structures, which doesn't really help your case.

How to check if one of the words in an NSString starts with a certain string? [duplicate]

Initial Googling indicates that there's no built-in way to do regular expressions in an Objective-C Cocoa application.
So four questions:
Is that really true?
Are you kidding me?
Ok, then is there a nice open-source library you recommend?
What are ways to get close enough without importing a library, perhaps with the NSScanner class?
I noticed that as of iOS 4.0 Apple provides a NSRegularExpression class. Additionally, as of 10.7, the class is available under OS X.
Yes, there's no regex support in Cocoa. If you're only interested in boolean matching, you can use NSPredicate which supports ICU regex syntax. But usually you're interested in the position of the match or position of subexpressions, and you cannot get it with NSPredicate.
As mentioned you can use regex POSIX functions. But they are considered slow, and the regex syntax is limited compared to other solutions (ICU/pcre).
There are many OSS libraries, CocoaDev has an extensive list.
RegExKitLite for example doesn't requires any libraries, just add the .m and .h to your project.
(My complaint against RegExKitLite is that it extends NSString via category, but it can be considered as a feature too. Also it uses the nonpublic ICU libraries shipped with the OS, which isn't recommended by Apple.)
RegexKit is the best I've found yet. Very Cocoa:y. I'm using the "Lite" version in several of our iPhone apps:
sourceforge
lingonikorg
You can use the POSIX Regular Expressions library (Yay for a POSIX compliant OS). Try
man 3 regex
The cheap and dirty hack solution that I use to solve REGEX and JSON parsing issues is to create a UIWebView object and inject Javascript function(s) to do the parsing. The javascript function then returns a string of the value (or list of values) I care about. In fact, you can store a small library set of functions customized for particular tasks and then just call them as needed.
I don't know if it this technique scales to huge volumes of repeated parsing requests, but for quick transactional stuff it gets the job done without depending on any extra external resources or code you might not understand.
I like the AGRegex framework which uses PCRE, handy if you are used to the PCRE syntax. The best version of this framework is the one in the Colloquy IRC client as it has been upgraded to use PCRE 6.7:
http://colloquy.info/project/browser/trunk/Frameworks/AGRegex
It's very lightweight, much more so than RegExKit (although not as capable of course).
NSRegularExpression is available since Mac OS X v10.7 and IOS 4.0.
During my search on this topic I came across CocoaOniguruma which uses Oniguruma, the Regular Expression engine behind Ruby1.9 and PHP5. It seems a bit newer compared to the existing OregKit (in Japanese). Not sure how these stack up against other bindings.
Googling alittle, found this library:
RegexOnNSString
Open source library, containing functions like:
-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement caseInsensitive:(BOOL)ignoreCase
and using NSRegularExpression class. Quite easy to use and no need to worry about anything.
Please, note that NSRegularExpression is available since Mac OS X v10.7 and IOS 4.0, as Datasmid mentioned.
I make it easy. I add a new C++ file to my Objective C project, rename it as .mm, and then create a standard C++ class inside. Then, I make a static class method in the "public:" section for a C++ function that takes an NSString and returns an NSString (or NSArray, if that's what you want). I then convert NSString to C++ std::string like so:
// If anyone knows a more efficient way, let me know in the comments.
// The "if" condition below is because ObjC crashes if converting to
// std::string if the string is nil or empty.
// assume #include <string>
std::string s = "";
if (([sInput != nil]) && (!([sInput isEqualTo:#""]))) {
std::string sTemp([sInput UTF8String]);
s = sTemp;
}
From there, I can use regex_replace like so:
// assume #include <regex>
std::string sResult = std::regex_replace(sSource,sRegExp,sReplaceWith);
Then, I can convert that std::string back into an NSString with:
NSString *sResponse2 = #(sResult.c_str());
If you're only using this C++ just for this function, then you may find it suitable to call this file extra.mm (class name Extra) and put this static class method in, and then add other static class methods when the situation arrives where it just makes sense to do it in C++ because it's less hassle in some cases. (There are cases where ObjC does something with less lines of code, and some cases where C++ does it with less lines of code.)
P.S. Still yet another way with this is to use a .mm file but make an Objective C wrapper around the use of std::string and std::regex_replace() (or regex_match()).

Using #properties for all instance variables coding standards

My coding team has chosen implement a coding standard of using #property's for all instance ivars. For publicly facing things, we of course define them in our .h files, but for our private things, we define them in the .m file in an interface above our implementation.
Does it matter if I refer to them as self.myvar = whatever or as [self setMyvar:whatever]? It doesn't seem to matter at all to me, and there seems to be a great deal of mixing one way or the other in our code base.
self.myvar = whatever
is syntactic sugar for
[self setMyvar:whatever]
They're exactly the same thing. No difference at all.
As others have indicated, foo.bar and [foo bar] are equivalent (save for the additional type requirements on the former, but that is minor).
FWIW, our team decided to eschew the dot syntax completely. The motivation is to avoid ambiguity; a message send always looks like a message send and .s are always used to access structure members.
We also limit our use of #{} and #[] to the creation of collections only. All accesses are done via indexOfObject:, objectForKey:, etc...
As well, we use ARC everywhere save for a couple of border files that sit between ObjC and C++. And we have the static analyzer turned on for all DEBUG builds and all warnings are treated as hard errors. We've also turned on just about every compiler warning that is practical (there are some that simply aren't practical to use).
There is plenty of similar questions.
In our coding standards, we don't care about using dot notation or method to access the property. We even sometimes use dot notation for methods which are not formally declared as property because with library methods it's sometimes hard to know without checking the docs and it doesn't make a difference.
It never makes sense to forbid direct method calls (hard to enforce).
I saw coding standards forbidding the dot notation.
In general I tend to prefer dot notation because it enables me to split assignments into visually separated parts, e.g.
self.a = x;
against
[self setA:x];
The second just seems less readable to me but it's a matter of personal taste.
On the other hand, sometimes it's easier to use the method directly, e.g. when you have the object as an id and you would have to cast to use the dot notation.
I think that mixing both is a good solution. Choose the one that will increase the readibility at the given place.
self.myVar = x is actually compiled to [self setMyVar: x];. There's no run-time difference.
However; for ease of code readability, I'd advise sticking with one scheme or the other. If you've already had properties enforced, it'd be better to leave everything in the dot notation - if for no other reason than because this allows your code to be more easily searched.

Resources