How to use NSAssert in iOS

How to use NSAssert in iOS
COMMENTS ()
Tweet

Hi Guys,

In this post we’ll look at how you can use NSAssert in iOS, specifically the best practices or Do’s and Don’ts when using this function. First let’s look at the recommended practices or the Do’s.

How to use NSAssert in iOS – the Do’s

You can use the NSAssert command in your function to make sure a certain condition does not occur or a certain value isn’t passed to the function that may cause problems in your app. For example, if you want a parameter in your method/function to always be a string, you can use the NSAssert command to make sure that it is, otherwise the app will break without going any further. By using NSAssert, you will also be able to track the issue better, making it easier to debug.

Let’s look at an example.

How to Use NSAssert in iOS

Here, if you don’t pass a string as a parameter your app will break. Thus by using the NSAssert function here you can basically nip the issue in the bud. Additionally, you can provide a description with the NSAssert function as well, which will help explain its use during code reviews or debugging sessions. For example:

How to Use NSAssert in iOS

Now let’s look at the Don’ts.

How to use NSAssert in iOS – the Don’ts

You must make sure that you never assign a value inside the NSAssert function because if you do, the function won’t get called in Release mode. Take a look at the sample code below.

How to Use NSAssert in iOS

In the above example, if we assign a value inside NSAssert, then ‘aString’ will get populated in debug mode but not in release mode. We recently made the same mistake while working on a project. We had assigned a value inside NSAssert and as a result, our app started to crash at random. It took us a couple of days to identify the value assignment inside the NSAssert function as the cause.

If you follow these guidelines you’ll save yourself a lot of hassle and debugging time.

Explore our blog

ABOUT FOLIO3

As a leading mobile app development company (iPhone, Android, Windows Phone, HTML5 app development), Folio3 specializes in native app development services and cross platform mobile app development services for the iPhone and iPad. We also offer extensive mobile app testing and QA services. If you have a mobile app idea that you’d like to discuss please or would like to know more about our iPhone app development services, please Contact Us. Learn more about our iPhone, Android and Windows Phone app development services

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812