Skip to main content

iOS codes snippets

source: image
NSString *path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"];
myImage = [UIImage imageWithContentsOfFile:path];
2.change the background  of selected cell
UIView *myview = [[UIView alloc] init];
myview.frame = CGRectMake(0, 0, 320, 47);
myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
cell.selectedBackgroundView = myview;
3.Append button to the soft keyboard:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; //addObserver:注册一个观察员name:消息名称
- (void)keyboardWillShow:(NSNotification *)note {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
[doneButton setImage:[UIImage imageNamed:@"5.png"] forState:UIControlStateNormal];
[doneButton addTarget:self action:@selector(addRadixPoint) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];//返回应用程序window
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) //遍历window上的所有subview
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard view found; add the custom button to it
if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
NSString *boundle = [[NSBundle mainBundle] resourcePath];
[web1 loadHTMLString:[NSString stringWithFormat:@"<img src="" rel="nofollow"/>
[cell.img loadHTMLString:[NSString stringWithFormat:@"<html><body><img src="" rel="nofollow"/>
NSString *javaScript1 = @"document.getElementsByName('.u').item(0).value";
NSString *javaScript2 = @"document.getElementsByName('.challenge').item(0).value";
NSString *strResult1 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript1]];
NSString *strResult2 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript2]];
utf8Str //
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];
[self performSelector:@selector(loginToNext) withObject:nil afterDelay:2];//黄色段为方法名,和延迟几秒执行.
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES; //opaque是否透明
[self.view addSubview:myImage];
[myImage release];
CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress = @"";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self addSubview:webView];
[webView release];
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
NSArray *myImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"myImage1.png"], [UIImage imageNamed:@"myImage2.png"], [UIImage imageNamed:@"myImage3.png"], [UIImage imageNamed:@"myImage4.gif"], nil];
UIImageView *myAnimatedView = [UIImageView alloc];
[myAnimatedView initWithFrame:[self bounds]];
myAnimatedView.animationImages = myImages; //animationImages属性返回一个存放动画图片的数组
myAnimatedView.animationDuration = 0.25; //浏览整个图片一次所用的时间
myAnimatedView.animationRepeatCount = 0; // 0 = loops forever动画重复次数
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
[myAnimatedView release];
动画:显示了something在屏幕上移动。注:这种类型的动画是“开始后不处理” -你不能获取任何有关物体在动画中的信息(如当前的位置)。如果您需要此信息,您会手动使用定时器去调整动画的X和Y坐标
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
//Creates and returns an CAPropertyAnimation instance for the specified key path.
//parameter:the key path of the property to be animated
theAnimation.fromValue=[NSNumber numberWithFloat:0];
theAnimation.toValue=[NSNumber numberWithFloat:-60];
[view.layer addAnimation:theAnimation forKey:@"animateLayer"];
Draggable items
Here's how to create a simple draggable image.
1. Create a new class that inherits from UIImageView
@interface myDraggableImage : UIImageView { }
2. In the implementation for this new class, add the 2 methods:
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
// Retrieve the touch point
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
// Move relative to the original touch point
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame];
3. Now instantiate the new class as you would any other new image and add it to your view
dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
[dragger setImage:[UIImage imageNamed:@"myImage.png"]];
[dragger setUserInteractionEnabled:YES];
1. Create the new thread:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
2. Create the method that is called by the new thread:
- (void)myMethod
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];
//What if you need to do something to the main thread from inside your new thread (for example, show a loading //symbol)? Use performSelectorOnMainThread.
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];
Plist files
Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user's Documents folder, and if not it should copy the plist from the app bundle.
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.plist", plistName] ];
[myPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] )
NSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
//Now read the plist file from Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
//Now read and set key/values
myKey = (int)[[plist valueForKey:@"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
[plist setValue:myKey forKey:@"myKey"];
[plist writeToFile:path atomically:YES];
Show a simple alert with OK button.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:
@"An Alert!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
Info button
Increase the touchable area on the Info button, so it's easier to press.
CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50);
[infoButton setFrame:newInfoButtonRect];
Detecting Subviews
You can loop through subviews of an existing view. This works especially well if you use the "tag" property on your views.
for (UIImageView *anImage in [self.view subviews])
if (anImage.tag == 1)
{ // do something }
14.UITableViewCell选 中的自定义样式
cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:cell.frame] autorelease];
cell.selectedBackgroundView.backgroundColor = [UIColor xxxxxx];
cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellart.png"]] autorelease];
cell.textLabel.highlightedTextColor = [UIColor xxxcolor];
sudo tmutil disablelocal
sudo /Developer/Library/uninstall-devtools --mode=all
sudo /Developer-3.2.2/Library/uninstall-devtools --mode=all
sudo tmutil enablelocal
1 chflags nohidden ~/Library
1 chflags hidden ~/Library
NSString *homeDir = NSHomeDirectory();
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *tmpDir = NSTemporaryDirectory();
seachBar=[[UISearchBar alloc] init];
seachBar.backgroundColor=[UIColor clearColor];
[[searchbar.subviews objectAtIndex:0]removeFromSuperview];
for (UIView *subview in seachBar.subviews)
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
[subview removeFromSuperview];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"40-di.png"]];
[mySearchBar insertSubview:imageView atIndex:1];
[imageView release];
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
searchBar.showsScopeBar = YES;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:YES animated:YES];
return YES;
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
searchBar.showsScopeBar = NO;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:NO animated:YES];
return YES;
for(id cc in [searchBar subviews])
if([cc isKindOfClass:[UIButton class]])
UIButton *btn = (UIButton *)cc;
[btn setTitle:@"搜索" forState:UIControlStateNormal];
1. preferences->downloads->documentation->check and install now 不过不一定起作用如果不起作用就参考下面的方法
2. 选中iOS 5.0 Library 然后点列表左下角的向上箭头然后把feed的地址复制到safari里可以找到相应的library包把它下下来(xar文件)然后在terminal里用"xar -xf 文件名"解压缩得到docset文件把这个文件复制到installed location指示的位置替换掉原文件最后把这个文件(包括其内部文件)的owner改成devdocs再把group改成wheel重启xcode就行
- (void) registerForKeyboardNotifications{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
- (void) keyboardWasShown:(NSNotification *) notif{
NSDictionary *info = [notif userInfo];
NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
CGRect scrollViewFrame= [scrollView frame];
scrollViewFrame.size.height -= keyboardSize.height;
scrollView.frame = scrollViewFrame;
[scrollView scrollRectToVisible:inputElementFrame animated:YES];
keyboardWasShown = YES;
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
- (NSString *)getMacAddress
int mgmtInfoBase[6];
char *msgBuffer = NULL;
size_t length;
unsigned char macAddress[6];
struct if_msghdr *interfaceMsgStruct;
struct sockaddr_dl *socketStruct;
NSString *errorFlag = NULL;
// Setup the management Information Base (mib)
mgmtInfoBase[0] = CTL_NET; // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE; // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK; // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
// With all configured interfaces requested, get handle index
if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
errorFlag = @"if_nametoindex failure";
// Get the size of the data available (store in len)
if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
errorFlag = @"sysctl mgmtInfoBase failure";
// Alloc memory based on above call
if ((msgBuffer = malloc(length)) == NULL)
errorFlag = @"buffer allocation failure";
// Get system information, store in buffer
if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
errorFlag = @"sysctl msgBuffer failure";
// Befor going any further...
if (errorFlag != NULL)
NSLog(@"Error: %@", errorFlag);
return errorFlag;
// Map msgbuffer to interface message structure
interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
// Map to link-level socket structure
socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
// Copy link layer address data in socket structure to an array
memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
// Read from char array into a string object, into traditional Mac address format
NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
macAddress[0], macAddress[1], macAddress[2],
macAddress[3], macAddress[4], macAddress[5]];
NSLog(@"Mac Address: %@", macAddressString);
// Release the buffer memory
return macAddressString;
2. 23排序
NSMutableArray*array = [[NSMutableArrayalloc]init];
NSArray*sortedArray = [arraysortedArrayUsingSelector:@selector(compare:)];
for(inti =0; i < [sortedArraycount]; i++)
intx = [[sortedArrayobjectAtIndex:i]intValue];
NSLog(@"######%d\n", x);
NSSortDescriptor* sortByA = [NSSortDescriptorsortDescriptorWithKey:@"x"ascending:NO];
Abstract:Constants returned by comparison functions, indicating whether a value is equal to, less than, or greater than another value.
kCFCompareLessThan= -1,
kCFCompareEqualTo= 0,
kCFCompareGreaterThan= 1
#import <Cocoa/Cocoa.h>
@implementation NSNumber (MySort)
- (NSComparisonResult) myCompare:(NSString *)other {
int result = ([self intValue]>>1) - ([other intValue]>>1);
return result < 0 ? NSOrderedDescending : result > 0 ? NSOrderedAscending : NSOrderedSame;
int main(int argc, char *argv[])
NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:[NSNumber numberWithInt:20]];
[array addObject:[NSNumber numberWithInt:1]];
[array addObject:[NSNumber numberWithInt:4]];
NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(myCompare:)];
for(int i = 0; i < [sortedArray count]; i++)
int x = [[sortedArray objectAtIndex:i]intValue];
NSLog(@"######%d\n", x);
NSArray *familyNames = [UIFont familyNames];
for( NSString *familyName in familyNames ){
printf( "Family: %s \n", [familyName UTF8String] );
NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
for( NSString *fontName in fontNames ){
printf( "\tFont: %s \n", [fontName UTF8String] );
5.然后在你的工程的Info.plist文件中新建一行(Add Row),添加key为:UIAppFonts,类型为Array或Dictionary都行;在UIAppFonts下再建立一个键值对,key为:Item 0,添加Value为XXX.ttf(你字体的名字,string型),可以添加多个
6.在你的项目里要用字体的时候 xx.font = [UIFont fontWithName:@"MicrosoftYaHei" size:20.0],这样就可以了。
NSURL*url=[NSURL URLWithString:@"prefs:root=WIFI"];
[[UIApplication sharedApplication] openURL:url];
About — prefs:root=General&path=About
Accessibility — prefs:root=General&path=ACCESSIBILITY
Airplane Mode On — prefs:root=AIRPLANE_MODE
Auto-Lock — prefs:root=General&path=AUTOLOCK
Brightness — prefs:root=Brightness
Bluetooth — prefs:root=General&path=Bluetooth
Date & Time — prefs:root=General&path=DATE_AND_TIME
FaceTime — prefs:root=FACETIME
General — prefs:root=General
Keyboard — prefs:root=General&path=Keyboard
iCloud — prefs:root=CASTLE
iCloud Storage & Backup — prefs:root=CASTLE&path=STORAGE_AND_BACKUP
International — prefs:root=General&path=INTERNATIONAL
Location Services — prefs:root=LOCATION_SERVICES
Music — prefs:root=MUSIC
Music Equalizer — prefs:root=MUSIC&path=EQ
Music Volume Limit — prefs:root=MUSIC&path=VolumeLimit
Network — prefs:root=General&path=Network
Nike + iPod — prefs:root=NIKE_PLUS_IPOD
Notes — prefs:root=NOTES
Notification — prefs:root=NOTIFICATIONS_ID
Phone — prefs:root=Phone
Photos — prefs:root=Photos
Profile — prefs:root=General&path=ManagedConfigurationList
Reset — prefs:root=General&path=Reset
Safari — prefs:root=Safari
Siri — prefs:root=General&path=Assistant
Sounds — prefs:root=Sounds
Software Update — prefs:root=General&path=SOFTWARE_UPDATE_LINK
Store — prefs:root=STORE
Twitter — prefs:root=TWITTER
Usage — prefs:root=General&path=USAGE
VPN — prefs:root=General&path=Network/VPN
Wallpaper — prefs:root=Wallpaper
Wi-Fi — prefs:root=WIFI
@interface UIDevice (ProcessesAdditions)
- (NSArray *)runningProcesses;
// .m
#import <sys/sysctl.h>
@implementation UIDevice (ProcessesAdditions)
- (NSArray *)runningProcesses {
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
size_t miblen = 4;
size_t size;
int st = sysctl(mib, miblen, NULL, &size, NULL, 0);
struct kinfo_proc * process = NULL;
struct kinfo_proc * newprocess = NULL;
do {
size += size / 10;
newprocess = realloc(process, size);
if (!newprocess){
if (process){
return nil;
process = newprocess;
st = sysctl(mib, miblen, process, &size, NULL, 0);
} while (st == -1 && errno == ENOMEM);
if (st == 0){
if (size % sizeof(struct kinfo_proc) == 0){
int nprocess = size / sizeof(struct kinfo_proc);
if (nprocess){
NSMutableArray * array = [[NSMutableArray alloc] init];
for (int i = nprocess - 1; i >= 0; i--){
NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName", nil]];
[processID release];
[processName release];
[array addObject:dict];
[dict release];
return [array autorelease];
return nil;
// Example usage.
NSArray * processes = [[UIDevice currentDevice] runningProcesses];
for (NSDictionary * dict in processes){
NSLog(@"%@ - %@", [dict objectForKey:@"ProcessID"], [dict objectForKey:@"ProcessName"]);
27 Objective-C中isMemberOfClass&isKindOfClass的应用举例
@interface Test : NSObject?{?}?-(void)print;?@end?@implementation Tset?-(void)print?{?printf(“This is Test.\n”);?}?@end
isMemberOfClass方法是来确定对象是否是某一个类的成员。?我们可以用这个方法来验证一个特定的对象是否是一个特定的类成员。?Test *test=[Test new];?if ([test isKindOfClass: [Test class]]==YES) {?Nslog(@”Test ok”);?}?if ([test isKindOfClass: [NSObject class]]==YES) {?Nslog(@”NSObject ok”);?}?—–?Test ok?isKindOfClass方法是来确定对象是否是某一个类的成员,或者是派生自该类的成员。?isMemberOfClass和isKindOfClass之间区别是:我们可以使用isKindOfClass来确定一个对象是否是一个类的成员,或者是派生自该类的成员。?例如:我们已经成NSObject派生了自己的类,isMemberOfClass不能检测任何的类都是基于NSObject类这一事实,而isKindOfClass可以。?Test *test=[Test new];?if ([test isKindOfClass: [Test class]]==YES) {?Nslog(@”Test ok”);?}?if ([test isKindOfClass: [NSObject class]]==YES) {?Nslog(@”NSObject ok”);?}?—–?Test ok?NSObject ok
28. 方法实现和协议遵循
在代码中,您可以在类似的情况下使用这些方法。通过这些方法,您可以在将消息或消息集合发送给某些潜在的匿名对象之前,确定它们是否可以正确地进行响应。在发送消息之前进行检查可以避免由不能识别的选择器引起的运行时例外。在实现非正式协议(这种协议是委托技术的基础)时,Application Kit就是在调用委托方法之前检查委托对象是否实现该方法(通过respondsToSelector:方法)。
列表2-9 使用respondsToSelector:方法
- (void)doCommandBySelector:(SEL)aSelector {
if ([self respondsToSelector:aSelector]) {
[self performSelector:aSelector withObject:nil];
} else {
[_client doCommandBySelector:aSelector];
列表2-10 使用conformsToProtocol:方法
// ...
if (!([((id)testObject) conformsToProtocol:@protocol(NSMenuItem)])) {
NSLog(@"Custom MenuItem, '%@', not loaded; it must conform to the
'NSMenuItem' protocol.\n", [testObject class]);
[testObject release];
testObject = nil;
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *strName = [[NSString alloc] initWithCString:pChar encoding:enc];
wchar_t *pWChar = (wchar_t*)[strName cStringUsingEncoding:NSUTF32StringEncoding];
[strName release];
#import <time.h>
#import <mach/mach_time.h>
srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF));
float rotateAngle = M_PI;
CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);
imageView.transform = transform;
select * from tb_name limit 10 offset 1
注:limit 10表示只显示10行记录,offset表示从索引号为1的记录开始,第一行的索引号为0
m_tableView.contentOffseta = CGPointMake(m_tableView.contentOffset.x, -65.0);
[_refreshHeaderView egoRefreshScrollViewDidEndDragging:m_tableView];
a1 =@"This is a1";
a2 =@"This is a2";
a3 =@"This is a3";
for (int i =0; i <3; i++) {
NSString *var = [NSStringstringWithFormat:@"a%d",i +1];
Ivar ivar =object_getInstanceVariable(self,var.UTF8String,NULL);
NSString *str = (NSString *)object_getIvar(self, ivar);


Popular posts from this blog

Stretch a row if data overflows in jasper reports

It is very common that some columns of the report need to stretch to show all the content in that column. But  if you just specify the property " stretch with overflow' to that column(we called text field in jasper report world) , it will just stretch that column and won't change other columns, so the row could be ridiculous. Haven't find the solution from internet yet. So I just review the properties in iReport one by one and find two useful properties(the bold highlighted in example below) which resolve the problems.   example:
<band height="20" splitType="Stretch"> <textField isStretchWithOverflow="true" pattern="" isBlankWhenNull="true"> <reportElement stretchType="RelativeToTallestObject" mode="Opaque" x="192" y="0" width="183" height="20"/> <box leftPadding="2"> <pen lineWidth="0.25"/> …

JasperReports - Configuration Reference

Spring - Operations with jdbcTemplate

This class manages all the database communication and exception handling using a java.sql.Connection that is obtained from the provided DataSource. JdbcTemplate is a stateless and threadsafe class and you can safely instantiate a single instance to be used for each DAO.

Use of Callback Methods
JdbcTemplate is based on a template style of programming common to many other parts of Spring. Some method calls are handled entirely by the JdbcTemplate, while others require the calling class to provide callback methods that contain the implementation for parts of the JDBC workflow. This is another form of Inversion of Control. Your application code hands over the responsibility of managing the database access to the template class. The template class in turn calls back to your application code when it needs some detail processing filled in. These callback methods are allowed to throw a java.sql.SQLException, since the framework will be able to catch this exception and use its built-in excepti…