Archive for the ‘Snippets’ category

NSLog Format Specifiers

February 19th, 2012
%@     Object
%d, %i signed int
%u     unsigned int
%f     float/double

%x, %X hexadecimal int
%o     octal int
%zu    size_t
%p     pointer
%e     float/double (in scientific notation)
%g     float/double (as %f or %e, depending on value)
%s     C string (bytes)
%S     C string (unichar)
%.*s   Pascal string (requires two arguments, pass pstr[0] as the first, pstr+1 as the second)
%c     character
%C     unichar

%lld   long long
%llu   unsigned long long
%Lf    long double

Presenting HttpServletResponse as file download

June 17th, 2011

The following code will present the response as a file to be download instead of being displayed in the browser. The key here is the Content-disposition header.

protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException
{
	byte[] data = null;
	// load data
 
	resp.reset();
	resp.setContentType("image/png");
	resp.setHeader("Content-disposition", "attachment; filename=image.png");
 
	final OutputStream output = resp.getOutputStream();
	output.write(data);
	output.close();
}

NSLog(“Hello world!”)

May 27th, 2011

Everybody knows logging is an import step during any software development, specially in the debug phase. However, its removal can be very tricky after the debug phase is finished and logging is no longer needed and you might need to get rid of it. That’s when macros are very helpful…

#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif
 
// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

With the code above, you can use DLog to log only while debugging and ALog to log always.

You can put this code to your .pch file or creat a new file (for example, Log.h) that you can reuse among various projects and import it whenever you need or in the .pch file again.

#import “Log.h”

For this to work you need to add the -DDEBUG flag in the “Other C Flags” option in your project’s configuration.

Another simpler way would be:

#ifdef DEBUG
#	define DLog(...) NSLog(__VA_ARGS__)
#else
#	define DLog(...) /* */
#endif
#define ALog(...) NSLog(__VA_ARGS__)