Posts Tagged ‘Objective-C’

Swiftification and Objective-C

Since Apple introduced Swift, they started to introduce things which were against Objective-C/SmallTalk philosophy.

Unlike Simula/C++ school, SmallTalk/Objective-C school valued simplicity and minimality.
Compared to Simula/C++, Objective-C folks/community has been very selective when they introduce new features to the language, while C++ community tended to add whatever people asked and whatever looked good. I like C++ in 1990’s. However, there are too many syntactic sugars and some functionalities which are not really necessary.

I know current generation of people. Instead of trying to understand philosophy behind their interested language, they just blame this and that about the language. To properly criticize in productive way, they should understand philosophy of the language. Only after that, in that boundary they should criticize the language.

So, people just blames how Objective-C is bad blah blah. Sure. it has its weak side. But once understand why it’s like that and what was its goal, it’s not that bad. Actually Objective-C with Cocoa is better than C++ with standard library or any framework.
Believe me. I am not narrow minded person. I’m a long time S/W engineer who learned many languages so far. Here in US, people just tend to stick to one thing and just see things from that point of view. It’s clearly seen when I got interviewed. They are only on one side.

Several years ago, ChangKi Kim and I have discussed a lot about those  ( and complaint a lot about current generation of people how narrow mind they had. ) Also, now I have pretty sufficient experience about people in the US. So, I can now say this is this and that is that.

Anyway, people here is self-centric, while we are relation-centric. So, it is clearly shown in conversation. When others say something different than mine, then we considers the situation he is under. And if what he says is right under that situation, we nod. However, people here don’t behave like that. They don’t care what kind of situation others are. Because such attitude, they can’t proplery criticize other languages or even asks something weird.

I’m the person who asked generics in Objective-C to Apple a while ago. ( about 10 years ago?)
Although I know that many things which can be achieved using generics can be solved by boxing (i.e. NSValue, NSNumber, and so on ), but some can’t be still. So, having generics is good, but I understood why Apple and Objective-C society say no to such idea.

However, now air is not like that.
Even when I visited Apple personally, now I see totally different people. Probably that’s the reason.
They look to behave more like Simula/C++ people.

In OS X 10.11, they introduced some syntactic sugar. I like some of them, but some are not really doubt able.

From this prelease AppKit Release Notes for OS X 10.11

Swiftification (New since WWDC Seed)
Framework APIs in both OS X 10.11 and iOS 9 have adopted new Objective-C features such as nullability, lightweight generics, and “kindof.” These features enable API intent to be expressed more precisely and APIs to come across better in Swift.

For instance we can now indicate that nil is a valid value for the destination view when converting an NSRect between coordinate systems:

– (NSRect)convertRect:(NSRect)rect toView:(nullable NSView *)view;

and that the array returned by splitting an NSString with componentsSeparatedByString: is an NSArray of NSStrings, and it will never be nil:

– (NSArray *)componentsSeparatedByString:(NSString *)separator;

I would like to talk about nullability.
In Objective-C, it’s perfectly OK to send messages to a null object. It has been like that and it has been considered as a virtue to have such null object-allowable behavior.
Null check on objects can be simplified thanks to that and that yields clear code.

However for the new nullability feature, they introduces nullable and nonnull keywords ( or _Nullable and _Nonnull ). It means that we need to care whether it can be null or not. It is good for people who have only C++ experience in their career. However,  from the point of Objective-C view, it’s not. It’s like to make Objective-C more like C++.
Then it’s to get rid of one of the strength of Objective-C.

I know that it’s due to Swift. Swift. ( That’s why they call it ‘Swiftification’. )
Swift is kind of collection of what all people asked to a computer language. So, some part of it looks like Pascal, some looks like Python, some looks like C#, some looks like C++ and so on.

I like Bibimbop, but I don’t like to mix almost everything and to believe “because I provide all the things people asked, it must be the best.”

Well, we already saw something similar happened in this industry:
PL/1 and arguably Java

UPDATE : By reading this page, I can see that it’s prepared for Swift/Objective-C interaction. Hmmm.. Ok, then. it’s Ok.

Some new additions in Objective-C : Nullability

After starting to work at Telestream, I don’t have time to write posts usually here. Actually more correct reason is that I don’t run into some subjects which interest me : Win32/MFC programming? Not doing much here. Here in-house framework is used although it’s written on top of Win32 and Cocoa/Carbon and sometimes I do touch those but not as much as I did before. Also, it’s not interesting to share such information here, because those frameworks/libraries are not used outside of this company.

.NET is not technically interesting or is almost same to Cocoa in its philosophy-wise. So, if I touch one subject in Cocoa, it’s also applicable to .NET or vice versa.

So, I feel like I’m behind of time, because I can’t catch up with their latest and greatest additions and changes.
Sometimes it suddenly makes me feel stupid and retarded. Here is one such thing : Nullability

Apple people nowadays don’t speak out things on fundamental stuffs. They like to speak out new functionality which attracts media journalists’ eyes rather than developers. ( Why are there so many non-developers who anticipates new products at WWDC? ) However to us, developers, this kind of fundamental changes are more interesting.
Here are some good blog posts. Please have your hands wet in them.

NSNotificationCenter with Blocks Considered Harmful

This is worth while to being shared!
http://sealedabstract.com/code/nsnotificationcenter-with-blocks-considered-harmful/

Very interesting bug of Objective-C

When a member variable (aka property in SmallTalk term, semantically same to @property, but member variables are called “property” in SmallTalk. ) is accessed using self.<property name> through the @property mechanism or just <member variable> name, sometimes the result is different.

different values

Difference between Objective-C compilation for Mac and iOS for 32 bit

For past several years, Apple people tried to make kernel for Mac and iOS identical.In Snow Leopard, they got rid of PowerPC code and started to introduce 64 bit kernel.

On Lion, as far as I know, kernel version of iOS caught up that of Mac OS X. So, after that it’s widely said that kernels for iOS and Mac are the same.
However, Apple recently introduced 64bit iOS for iOS 7. So, although the kernel for Mac was built as 64bit, iOS was built 32bit so far.
Anyway, the trend is that Cocoa becomes similar and Objective-C compiler becomes similar in feature list they support.

However, I noticed that 32bit compilation for Mac is not up-to-date compared to that for iOS.

Here is the difference between the two.

32bit compilation for Mac OS X (on the left) and iOS (on the right)

32bit compilation for Mac OS X (on the left) and iOS (on the right)

Although the overall direction is to make them identical on Mac OS X and iOS identical, it turns out that Apple didn’t update 32bit compilation for Mac to match that for iOS. The 64 bit runtime on Mac OS X is so called ‘modern run-time’. But should the run-time different for Mac and iOS?
I’m not sure because I don’t know the detailed story about what happened at Apple.

Because I have worked for iOS recently, i thought that 32 bit build environment for OS X would be the same to 32 bit environment for iOS. But it was not.
Apple’s official feature matrix can be found here.
What doesn’t catch is that modern runtime is only for 64 bit on Mac.

 

Spark Inspector : Its flexibity

Ok.. Using Spark Inspector was very easy.

At first there was one odd thing : Where is the SparkInspector.framework?
It’s located in Spark Inspector app. However, if using its “Framework Setup assistant”, the app ingest frameworks to be linked for a chosen project for you.

One thing I didn’t like was that.. as most Cocoa programmers tend to set up a Xcode project, it puts framework setting in “target” Build Settings rather than “Project” Build Settings.

link settingIf you want to set those links as default for all targets you end up adding, the easier way is to put that setting in “project” Build Settings. I know that many Mac/iOS app developers who usually jumped into Mac/iOS app dev. after iOS became popular don’t understand the different necessity between the “Target” and “Project” Build Settings.
Anyway, this is not a big deal.

Now, let’s talk about cool things.

Spark Inspector app

As you can see from the above picture, your app runs on a simulator or an actual device while debugging, but the Spark Inspector app intercept that also and displays view hierarchy in list form on its left pane, visual representation of it in the middle pane, and finally, properties of chosen view/layers on the right-most pane. So, while you are debugging and interacting with a real device or a simulator, you can change colors, tints etc by choosing a layer/view on the Spark Inspector and changes some properties of them.
You don’t need to paint your layer/view in your code for debugging purpose anymore!
Isn’t that cool?

Also, the most important and useful feature of this app is the 3D display of those views and layers. When one view occludes an underlying view completely, and if there is some transition is applied to the underlying view ( unexpectedly ), you can still check what’s happening visually.

You can say that recursiveDescription is good enough. (It’s undocumented message of UIView )
However, when there are lots of view/layers, it can be very hard to identify which one is which when you use the message. However, this great helper tool for UI debugging eases debugging very easy.

After the PaintCode, I think this is a must-have tool for iOS developers!
I’ll buy it soon.

BTW, there is one little glitch there. As you can see, the right side of the right-most pane invades the right border of its super view. So, the content on the right-most pane goes beyond the right border.

difference in auto synthesis and “traditional” synthesis

After the introduction of iPhone SDK, many things have been changed very quickly.
Some were changed very publicly, while some didn’t. Even though there is no explanation on those changes, you could figure out some by taking a look at basic template code which Xcode puts by default.
However, some are hidden.
I was away from iOS/Mac development for a while and tried to catch up stuff recently. One of the simple but astonishing one was the internal member variable Objective-C preprocessor creates.

For example, let’s say that interface file looks like this.

@interface JAWindowController : NSObject

@property (retain, nonatomic) IBOutlet UIToolbar *toolBar;
@property (retain, nonatomic) IBOutlet UIButton *buttonOne;
@property (retain, nonatomic) IBOutlet UITextView *textViewOne;

@end

Then when ARC is off and auto synthesis is used, it creates those internal variables which matches their properties with “_” prefixed to the property name.

#import "JAWindowController.h"

@implementation JAWindowController

- (void)dealloc
{
	[_buttonOne release];
	[_textViewOne release];
	[_toolBar release];
	[super dealloc];
}
@end

However, if explicit synthesis is used, it will create the default internal variable names same to their property names like this.

the red underlines means a variable with such a name doesn't exists.

the red underlines means a variable with such a name doesn’t exists.

When ARC is on, it’s the same like the case of ARC is off. The only difference is that it doesn’t create dealloc message for you automatically, because usually it’s not necessary because Objective-C objects are to be released automatically by ARC mechanism.

Getting camera resolution on iOS devices

Apple doesn’t provide easy to use class or messages to retrieve camera resolution. However, people are saying that there is a way to get the information.

So, based on that, I wrote this code.

- (void) setupVideoCaptureSession
{
	self.isSetUpOK = true;
	
	self.cameraCaptureSession = [[AVCaptureSession alloc] init];
	
	self.cameraCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
	bool isBackCamera = ([self.cameraCaptureDevice position] == AVCaptureDevicePositionBack);
	
	NSError *error;
//	NSLog( @"position : %@", ([defaultCaptureDevice position] == AVCaptureDevicePositionBack)? @"Back":@"Front" );
	if (isBackCamera)
	{
		self.cameraCaptureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.cameraCaptureDevice error:&error];

		if( error == nil )
		{
			// Start of bulk configruation :It's not really needed here, but just in case...
			[self.cameraCaptureSession beginConfiguration];
			
			if( [self.cameraCaptureSession canSetSessionPreset:AVCaptureSessionPresetPhoto] )
				self.cameraCaptureSession.sessionPreset = AVCaptureSessionPresetPhoto;
			
			// End of bulk configuration
			[self.cameraCaptureSession commitConfiguration];
			
			
			[self.cameraCaptureSession startRunning];
		}
		else
			self.isSetUpOK = false;
		
	}
	else
	{
		self.cameraCaptureDevice = nil;
		
		self.isSetUpOK = false;
	}
}

- (CMVideoDimensions) cameraResolutionDimension
{
	CMVideoDimensions resolutionDimension = { 0, 0 };
	
	if( self.isSetUpOK )
	{
		if( self.cameraCaptureSession.isRunning )
			NSLog( @"capture session is running.");
		else
			NSLog( @"capture session is not running");
		
		
		for( AVCaptureInputPort *port in self.cameraCaptureDeviceInput.ports )
		{
			if( [port mediaType] == AVMediaTypeVideo )
			{
				self.cameraCaptureInputPort = port;
				CMVideoFormatDescriptionRef descRef = [port formatDescription];
//				resolutionDimension = CMVideoFormatDescriptionGetDimensions([port formatDescription]);
				resolutionDimension = CMVideoFormatDescriptionGetDimensions(descRef);
			}
		}
	}
	
	return resolutionDimension;
}

If setupVideoCaptureSession and cameraResolutionDimension are called in that order, it should retrieve the camera resolution dimension in pixels. However, it doesn’t. A guy told me that it’s a bug. So, I filed it.

But I’m not sure. This is so apparent. How come Apple guys pass this stuff through their SQA process? As a person who have know their quality, it should not happen. Nowadays I notice lots of bugs in their tools, frameworks, etc. What’s happening in Apple nowadays?

Great tip to figure out view hierarchy

According to objcguy, you can figure out view hierarchy with one call.

http://msxfan.com/nsview-subtreedescription

Which one to use? NSTimer or timer dispatch_source?

Well, as I said in my previous post, Apple people don’t maintain AppKit framework as they did before.

So, as a developer you would need to decide functions from which framework to use. What I means is, for example when Apple introduced a feature in Core Graphics, a corresponding NS* class and its messages used the newly implemented feature in Core Graphics. So, you don’t really need to access Core Graphics directly except for some special cases where you need to access those lower level functions than AppKit directly.

However, now you will decide which one to use more frequently than you did so before.
For example, scheduledTimerWithTimeInterval:invocation:repeats of NSTimer doesn’t look to use the timer dispatch_source. if it uses timer dispatch_source internally, you will not need to worry about which one to use. But now you should do so.

There can be some reason you would prefer using NSTimer message.

  1. You have old source code which was written for OS X earlier than OS X 10.6 Snow Leopard and want to keep the source code
  2. You want to ensure source code level compatibility with older OS X. ( Well, you would say the version of Xcode required to build for the older OS is not installable on current Mac OS X. But if your company is serious about supporting older but still decent OS X, they should keep the dev. environment for you.
  3. You want to ensure source code level compatibility with GNUStep. ( I wonder how many people/companies actually care about GNUStep for commercial S/W. )
  4. You prefer the simple NSTimer use pattern.

However, you would prefer using the timer dispatch_source if you want :

  1. Better performance  and caring of multi-core architecture environment more well presumably
    • NSTimer is scheduled in Run-Loop, while dispatch_source is in GCD space. So, inherently dispatch_source will utilize multicore architecture more well, although it could be negligible practically.
  2. higher timer resolution ( NSTimer is in seconds, while dispatch_source is in nanosecond )
    • Probably this is the strongest reason you want to use dispatch_source.

Any other reason to prefer one to the other?